//Java代码 //package test.socket; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class TalkMe { public static void main(String[] args) { System.out.println("请输入:IP地址:"); TalkMe talk = new TalkMe(); talk.listener().start(); try { talk.talker(new BufferedReader(new InputStreamReader(System.in)).readLine()).start(); } catch (IOException e) { e.printStackTrace(); } } private Thread listener() { return new Thread() { public void run() { DataInputStream dataIS = null; String clientSay; try { ServerSocket server = new ServerSocket(9666); Socket socket = server.accept(); while (true) { dataIS = new DataInputStream(socket.getInputStream()); clientSay = dataIS.readLine(); System.out.println("Other say:" + clientSay); } } catch (IOException e) { e.printStackTrace(); } } }; } private Thread talker(final String ip) { return new Thread() { public void run() { Socket socket = null; InputStreamReader stdin=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(stdin); DataInputStream dataIS = new DataInputStream(System.in); OutputStream os; PrintStream ps; String say = ""; boolean flag = true; while (flag) { if (flag) System.out.println("connection ...."); try { socket = new Socket(ip, 9666); System.out.println("connection ok."); flag = true; os = socket.getOutputStream(); ps = new PrintStream(os); while (true) { say = dataIS.readLine(); ps.println(say); } } catch (UnknownHostException e) { try { sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } catch (IOException e) {} } } }; } }