Java代码
package testsocket;
import javaioBufferedReader;
import javaioDataInputStream;
import javaioIOException;
import javaioInputStreamReader;
import javaioOutputStream;
import javaioPrintStream;
import ServerSocket;
import Socket;
import UnknownHostException;
public class TalkMe {
public static void main(String[] args) {
Systemoutprintln(请输入:IP地址);
TalkMe talk = new TalkMe();
talklistener()start();
try {
talktalker(new BufferedReader(new InputStreamReader(Systemin))readLine())start();
} catch (IOException e) {
eprintStackTrace();
}
}
private Thread listener(){
return new Thread() {
public void run() {
DataInputStream dataIS = null;
String clientSay;
try {
ServerSocket server = new ServerSocket();
Socket socket = serveraccept();
while (true) {
dataIS = new DataInputStream(socketgetInputStream());
clientSay = dataISreadLine();
Systemoutprintln(Other say: + clientSay);
}
} catch (IOException e) {
eprintStackTrace();
}
}
};
}
private Thread talker(final String ip){
return new Thread(){
public void run() {
Socket socket = null;
InputStreamReader stdin=new InputStreamReader(Systemin);
BufferedReader br=new BufferedReader(stdin);
DataInputStream dataIS = new DataInputStream(Systemin);
OutputStream os;
PrintStream ps;
String say = ;
boolean flag = true;
while (flag) {
if (flag)
Systemoutprintln(connection );
try {
socket = new Socket(ip );
Systemoutprintln(connection ok);
flag = true;
os = socketgetOutputStream();
ps = new PrintStream(os);
while (true) {
say = dataISreadLine();
psprintln(say);
}
} catch (UnknownHostException e) {
try {
sleep();
} catch (InterruptedException e) {
eprintStackTrace();
}
} catch (IOException e) {
}
}
}
};
}
}