我在编写一通讯程序 实行多线程通讯的,一个服务器端,多个客户端间的通讯,如何加入生产者与消费者线程。
客户端:
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]){
try{
Socket socket=new Socket("127.0.0.1",4700);//向本机的4700端口发出客户请求
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
PrintWriter os=new PrintWriter(socket.getOutputStream());
String readline;
readline=sin.readLine();
while(!readline.equals("bye"))
{ os.println(readline);
os.flush();
System.out.println("Server:"+is.readLine());
//从Server读入一字符串,并打印到标准输出上
readline=sin.readLine();
}
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e);//出错,则打印出错信息
}
}
}
服务端:
import java.io.*;
import java.net.*;
import java.applet.Applet;
import java.lang.Thread;
class ServerThread extends Thread
{ Socket socket=null;
int clientnum;
public ServerThread(Socket socket,int num)
{this.socket=socket;
clientnum=num+1;
}
public void run()
{try
{BufferedReader is =new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os=new PrintWriter(socket.getOutputStream());
os.println("线程"+clientnum+'\n');//向客户端输出该字符串
os.flush();
System.out.println("线程"+clientnum);
String aa;
while(true)
{ if(is.ready())
{ aa=is.readLine();System.out.println("Client:"+aa);
os.println("Server output "+aa+'\n');//向客户端输出该字符串
os.flush();
}
}
}
catch(Exception e)
{System.out.println(1);
}
}
}
public class TalkServer{
public static void main(String args[]){
try{
ServerSocket serverSocket=null;
boolean listening=true;
try{
serverSocket=new ServerSocket(4700);//创建一个ServerSocket在端口4700监听客户请求
}catch(IOException e){
}
int clientnum=0;
while(listening)
{new ServerThread(serverSocket.accept(),clientnum).start();
clientnum++;
}
serverSocket.close(); //关闭ServerSocket
}catch(Exception e){
System.out.println("Error:"+e); //出错,打印出错信息
}
}
}