?? threadclient.java
字號:
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 + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -