tcpServer
public class tcpServer {
public static final int PORT = 1234;
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(PORT);
try {
while (true) {
Socket socket = s.accept();
Thread thread=new Thread(new ServerThread(socket));
thread.start();
}
} finally {
s.close();
}
}
}
tcpClient.java
public class tcpClient {
public static void main(String[] args) throws IOException {
Socket socket = null;
int N=5;
for (int i = 0; i < N; i++) {
socket = new Socket("127.0.0.1", 1234);
}
try {
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
for (int i = 0; i < N; i++) {
dos.writeUTF("测试:" + i);
dos.flush();
System.out.println(dis.readUTF());
}
dos.writeUTF("end");
dos.flush();
dos.close();
dis.close();
} finally {
socket.close();
}
}
}
ServerThread.java
public class ServerThread implements Runnable {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
DataInputStream dis = new DataInputStream(ss.getInputStream());
DataOutputStream dos = new DataOutputStream(ss.getOutputStream());
while (true) {
String str = dis.readUTF();
if (str.equals("end"))
break;
System.out.println(str);
dos.writeUTF("Echoing:" + str);
}
dos.close();
dis.close();
} catch (Exception e) {
}
}
}