日期:2014-05-20 浏览次数:20908 次
package com.cfpl.q; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerMain { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(5000); while (true) { Socket socket = serverSocket.accept(); ServerReadThread sr = new ServerReadThread(socket); ServerWriterThread sw = new ServerWriterThread(socket); sr.start(); sw.start(); } } }
package com.cfpl.q; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class ServerReadThread extends Thread { private Socket socket; public ServerReadThread(Socket socket) { this.socket = socket; } @Override public void run() { try { InputStream is = socket.getInputStream(); while (true) { byte[] bt = new byte[1024]; int length = is.read(bt); System.out.println(new String(bt,0,length)); // BufferedReader br = new BufferedReader(new InputStreamReader(is)); // String s = br.readLine(); // System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } } }
package com.cfpl.q; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; public class ServerWriterThread extends Thread { private Socket socket; public ServerWriterThread(Socket socket) { this.socket = socket; } @Override public void run() { try { OutputStream os = socket.getOutputStream(); while (true) { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); String s = br.readLine(); os.write(s.getBytes()); } } catch (IOException e) { e.printStackTrace(); } } }
package com.cfpl.q; import java.net.Socket; public class ClientMain { public static void main(String[] args) throws Exception { Socket socket = new Socket("127.0.0.1",5000); ClientReadThread cr = new ClientReadThread(socket); ClientWriterThread cw = new ClientWriterThread(socket); cr.start(); cw.start(); } }
package com.cfpl.q; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class ClientReadThread extends Thread { private Socket socket; public ClientReadThread(Socket socket) { this.socket = socket; } @Override public void run() { try { InputStream is = socket.getInputStream(); while (true) { byte[] bt = new byte[1024]; int length = is.read(bt); System.out.println(new String(bt,0,length)); // BufferedReader br = new BufferedReader( // new InputStreamReader(is)); // String s = br.readLine(); // System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } } }