50,530
社区成员
发帖
与我相关
我的任务
分享
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,5677);
}
catch(IOException e){
e.printStackTrace();
}
//实例化I/O对象
try{
in= new BufferedReader(new InputStreamReader
(socket.getInputStream()));
out= new PrintWriter(new OutputStreamWriter
(socket.getOutputStream()));
//开启线程
start();
}
catch(IOException e){
//出现异常,关闭socket
try{
socket.close();
}
catch(IOException e2){
e2.printStackTrace();
}
}
}
//线程主体方法
public void run(){
try{
out.print("Hello Server,My id is"+clientId);
@SuppressWarnings("unused")
String str=in.readLine();
System.out.print("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);
}
}
}
package tcp;
import java.io.*;
import java.net.*;
class ServerThreadCode extends Thread{
//客户端的socket
private Socket clientSocket;
//I/O句柄
private BufferedReader in;
private PrintWriter out;
//默认的构造函数
public ServerThreadCode(){}
//实际调用的构造函数
public ServerThreadCode(Socket s)throws IOException{
clientSocket=s;
//初始化in和out的句柄
in= new BufferedReader(new InputStreamReader
(clientSocket.getInputStream()));
out= new PrintWriter(new OutputStreamWriter
(clientSocket.getOutputStream()));
//开启线程
start();
}
//线程执行的主体函数
public void run(){
try{
//用循环来监听通信内容
for(;;){
String str=in.readLine();
//如果接收到的是byebye,退出本次通信
if(str.equals("byebye")){
break;
}
System.out.print("In Server reveived the info:"+str);
out.print(str);
}
System.out.print("closing the server socket!");
}
catch(IOException e){
e.printStackTrace();
}
finally{
System.out.print("close the Server socket and the io.");
try{
clientSocket.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
public class ThreadServer {
//端口号
static final int portNo=5677;
public static void main(String[] args)throws IOException{
//服务器端的socket
ServerSocket s=new ServerSocket(portNo);
System.out.print("The Server is start:"+s);
try{
for(;;){
//阻塞,知道有客户端连接
Socket socket=s.accept();
//通过构造函数,启动线程
new ServerThreadCode(socket);
}
}
finally{
s.close();
}
}
}