TCP_Socket
- 单向收发信息
/*Server.java*/ import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8888); while(true) { Socket s = ss.accept(); OutputStream os = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF("Hello " + s.getInetAddress() + "port#" + s.getPort()); dos.close(); s.close(); } } catch (IOException e) { e.printStackTrace(); System.out.println("程序运行出错:" + e); } } }
/*Clent.java*/ import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1", 8888); InputStream is = s.getInputStream(); DataInputStream dis = new DataInputStream(is); System.out.println(dis.readUTF()); dis.close(); s.close(); } catch (ConnectException e) { e.printStackTrace(); System.out.println("服务器连接失败!"); } catch (IOException e) { e.printStackTrace(); } } }
- 双向收发信息
/*Server.java*/ import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { InputStream in = null; OutputStream out = null; try { ServerSocket ss = new ServerSocket(8888); Socket s = ss.accept(); in = s.getInputStream(); out = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); DataInputStream dis = new DataInputStream(in); String str = null; if((str=dis.readUTF())!=null) { System.out.println(str); System.out.println("from: " + s.getInetAddress()); System.out.println("port: " + s.getPort()); } dos.writeUTF("Hello!"); dis.close(); dos.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } } }
/*Client.java*/ import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { InputStream is = null; OutputStream os = null; try { Socket s = new Socket("localhost", 8888); is = s.getInputStream(); os = s.getOutputStream(); DataInputStream dis = new DataInputStream(is); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF("Hello!"); String str = null; if((str=dis.readUTF())!=null) { System.out.println(str); } dos.close(); dis.close(); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }