Java编写TCP编程--回射信息实例
注:简单的tcp联系,还存在问题,readUTF()为阻塞型,如果之前的用户一直不输入,则一直阻塞,之后的用户再连接会出现问题。
1 import java.io.*; 2 import java.net.*; 3 4 //TCPServer.java 5 public class TCPServer { 6 public static void main(String[] args) throws IOException { 7 ServerSocket ss = new ServerSocket(6666); 8 while (true) { 9 Socket s = ss.accept(); 10 DataInputStream dis = new DataInputStream(s.getInputStream()); 11 System.out.println("Server:" + dis.readUTF()); 12 dis.close(); 13 s.close(); 14 } 15 } 16 }
1 import java.io.*; 2 import java.net.*; 3 4 //TCPClient.java 5 public class TCPClient { 6 public static void main(String[] args) throws IOException { 7 Socket s = new Socket("127.0.0.1", 6666); 8 OutputStream os = s.getOutputStream(); 9 DataOutputStream dos = new DataOutputStream(os); 10 dos.writeUTF("hello server"); 11 dos.flush(); 12 dos.close(); 13 s.close(); 14 } 15 }