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