import java.io.*;
import java.net.*;class ClientThread extends Thread {
private int id;
private Socket socket;
private BufferedReader reader;
private PrintWriter writer; public ClientThread(int id) { try {
// 发起到目的主机的8888号端口的连接套接字
socket = new Socket("localhost", 8888);
} catch (IOException e) {
System.out.println("连接请求失败!");
e.printStackTrace();
}
this.id = id;
try { reader = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (IOException e) {
try {
socket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
} } public void run() {
try {
for (int c = 0; c < 5; c++) {
writer.println("this is Thread:" + id + ": " + c);
System.out.println(reader.readLine());
}
} catch (IOException e) {
System.out.println("在发送或接收数据时发生错误。");
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
System.out.println("在关闭socket时发生错误!");
e.printStackTrace();
} }
}
}public class EchoClient {
public static void main(String[] args) throws IOException { for (int i = 0; i < 10; i++) { new ClientThread(i).start();
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
} }}
这是客户端的程序,为什么划线部分的代码,老运行出错,如果循环次数为1,就能通过。为什么?服务器端:
import java.io.*;
import java.net.*;public class EchoServer extends Thread {
private static ServerSocket server;
private Socket connection;
private BufferedReader reader;
private PrintWriter writer; public EchoServer(Socket connection) {
super();
this.connection = connection;
start();
} public void run() {
try { reader = new BufferedReader(new InputStreamReader(connection
.getInputStream())); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream())), true); // 参数true很重要 String str = reader.readLine();
System.out.println("收到客户端发来的信息了:" + str);
writer.println("返回:" + str);
} catch (IOException e) {
System.out.println("在读写数据的时候发生错误!");
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (IOException e) {
System.out.println("在关闭套接字的时候出现错误!");
e.printStackTrace();
}
}
} public static void main(String[] args) { try {
// 创建一个新的服务器端套接字对象
server = new ServerSocket(8888); while (true) {
Socket connection = server.accept();
new EchoServer(connection);
}
} catch (IOException e) {
System.out.println("在创建服务器端套接字时出现错误!");
e.printStackTrace();
} }}