threadclient.java
来自「本光盘包含了本书各章中出现的所有程序的源代码。 1. 如果是Java程序」· Java 代码 · 共 69 行
JAVA
69 行
package tcp;
import java.net.*;
import java.io.*;
class ClientThreadCode extends Thread {
// 客户端的socket
private Socket socket;
// 线程统计数,用来给线程编号
private static int cnt = 0;
private int clientId = cnt++;
private BufferedReader in;
private PrintWriter out;
// 构造函数
public ClientThreadCode(InetAddress addr) {
try {
socket = new Socket(addr, 3333);
} catch (IOException e) {
e.printStackTrace();
}
// 实例化IO对象
try {
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// 开启线程
start();
} catch (IOException e) {
// 出现异常,关闭socket
try {
socket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
// 线程主体方法
public void run() {
try {
out.println("Hello Server,My id is " + clientId);
String str = in.readLine();
System.out.println(str);
out.println("byebye");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ThreadClient {
public static void main(String[] args) throws IOException,
InterruptedException {
int threadNo = 0;
InetAddress addr = InetAddress.getByName("localhost");
for (threadNo = 0; threadNo < 3; threadNo++) {
new ClientThreadCode(addr);
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?