import java.net.*; import java.io.*; public class TestTCPServer { public static void main(String[] args) { InputStream in = null; OutputStream out = null; try { ServerSocket ss = new ServerSocket(8888); Socket socket = ss.accept(); in = socket.getInputStream(); out = socket.getOutputStream(); DataInputStream dis = new DataInputStream(in); DataOutputStream dos = new DataOutputStream(out); String s = null; if((s = dis.readUTF()) != null) { System.out.println(s); System.out.println("form:" + socket.getInetAddress()); System.out.println("port:" + socket.getPort()); } dos.writeUTF("Hi, hello"); dis.close(); dos.close(); socket.close(); } catch(IOException e) { e.printStackTrace(); } } } import java.net.*; import java.io.*; public class TestTCPClient { public static void main(String[] args) { InputStream in = null; OutputStream out = null; try { Socket socket = new Socket("localhost", 8888); in = socket.getInputStream(); out = socket.getOutputStream(); DataInputStream dis = new DataInputStream(in); DataOutputStream dos = new DataOutputStream(out); dos.writeUTF("Hey"); String s = null; if((s = dis.readUTF()) != null) { System.out.println(s); } dis.close(); dos.close(); socket.close(); } catch(UnknownHostException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } }
posted on 2012-05-06 13:07 spring学习笔记 阅读(295) 评论(0) 编辑 收藏 举报