本文主要是介绍java线程实现服务器与客户端互发消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
线程实现服务器与客户端互发消息
如果不用多线程来实现服务器与客户端互发消息则当一方发完消息后另一方才可以发,如果用了线程,因为多个线程可以同时执行,只要把发送和接收两个方法放入线程中让他们同时执行就可以实现服务器与客户端互发消息不受限制了
SendThread:
public class SendThread implements Runnable{DataOutputStream dataOutputStream;public SendThread(Socket socket) throws IOException {//把Socket传进方法,把要发送的内容送入SocketdataOutputStream= new DataOutputStream(socket.getOutputStream());}@Overridepublic void run() {while(true){Scanner scanner=new Scanner(System.in);String s=scanner.next();try {dataOutputStream.writeUTF(s);} catch (IOException e) {e.printStackTrace();}}}
}
ReceiveThread:
public class ReceiveThread implements Runnable{DataInputStream dataInputStream;ReceiveThread(Socket socket) throws IOException {//把Socket传进方法,得到Socket中的数据dataInputStream=new DataInputStream(socket.getInputStream());}@Overridepublic void run(){Thread thread=Thread.currentThread();while(true) {try {String s = dataInputStream.readUTF();if (thread.getName().equals("客户端")){System.out.println("服务器说:"+s);}if (thread.getName().equals("服务器")){System.out.println("客户端说:"+s);}} catch (IOException e) {e.printStackTrace();}}}
}
Server:
public static void main(String[] args) {try {ServerSocket serverSocket=new ServerSocket(7788);System.out.println("服务器启动成功");Socket socket=serverSocket.accept();System.out.println("有客户端连接到服务器");SendThread sendThread=new SendThread(socket);ReceiveThread receiveThread=new ReceiveThread(socket);Thread tse=new Thread(sendThread);Thread tre=new Thread(receiveThread,"服务器");tse.start();tre.start();} catch (IOException e) {e.printStackTrace();}}
Client:
public static void main(String[] args) {try {Socket socket=new Socket("192.168.124.185",7788);SendThread sendThread=new SendThread(socket);ReceiveThread receiveThread=new ReceiveThread(socket);Thread tse=new Thread(sendThread);Thread tre=new Thread(receiveThread,"客户端");tse.start();tre.start();} catch (IOException e) {e.printStackTrace();}}
这篇关于java线程实现服务器与客户端互发消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!