JAVA实现全双工通信(TCP/IP),简单多人聊天界面

该文章详细介绍了如何使用TCP/IP协议建立一个多台机器间的聊天系统。系统包括客户端和服务器端,客户端用于发送和接收信息,而服务器端负责信息的转发。代码示例使用Java编写,涉及到Socket编程,IP地址和端口的配置,以及IO流和多线程的运用,实现了客户端之间的聊天记录功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,思路和代码分析。

基于网络通信TCP/IP协议,通过ip地址实现多台机器进行通话。

实现多人聊天首先要分为客户端和服务器端,客户端用来互相发送信息和查看信息和保存聊天记录的功能,服务器端主要实现对客户端发来信息的转接,通过得到socket(套接字)对象并储存到容器里,然后对容器里的socket对象进行操作。注意ip地址和端口的正确与io流,和多线程的使用。

二,实现效果

客户端1和2之间的对话记录

 三,代码实现

1,界面代码

import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;


public class qqChat extends JFrame implements ActionListener
{
	
	JTextField inputField;
	static JTextArea outputArea;
	InputStream is;
	OutputStream os;
	Socket socket;
	
	
	
	public qqChat(Socket socket ) {
			super("聊天室");
			this.socket=socket;
			JPanel jp=new JPanel();
			this.setSize(550,550);
			jp.setSize(100,200);
			 inputField=new JTextField(20);  //文本段			
			JButton jb1=new JButton("send");
			JButton jb2=new JButton("clean");
			JButton jb3=new JButton("record");
		
			jb3.addActionListener(this);
			jb1.addActionListener(this);
			jb2.addActionListener(this);
		
			jb1.setActionCommand("send");
			jb2.setActionCommand("clean");
			jb3.setActionCommand("record");
			
			jp.setLayout(new FlowLayout());
			outputArea=new JTextArea(40,40);    //文本域
			JScrollPane jsp=new JScrollPane(outputArea);		//滚轴
			
			jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);			
			jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
			jsp.setPreferredSize(new Dimension(400,400)); 
			
			
			jp.add(jb3);
			jp.add(inputField);
			jp.add(jb1);
			jp.add(jb2);
			
			
	
			
		
			this.setLayout(new FlowLayout());
			this.add(jp);
			this.add(jsp);
			
			this.setLocationRelativeTo(null);
			this.setVisible(true);
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				
	}
		public void actionPerformed(ActionEvent e) {
		
		if (e.getActionCommand().equals("send"))
			{
				String  sendMsg  = inputField.getText() ;
                 ClientSendThread  sendThread  =  new  ClientSendThread(socket,  sendMsg);
                 sendThread.start();
				 inputField.setText("");
				 outputArea.append("客户端1:"+sendMsg+"\n");
			}			
		if (e.getActionCommand().equals("clean"))
			outputArea.setText("");
				
	}
	public static void main(String[] args) {
		Socket  socket=null;
		try  {
                           socket  =  new  Socket("localhost",  8888); 
						   new qqChat(socket);
                        ClientReceiveThread  receiveThread  =  new  ClientReceiveThread(socket, outputArea);
                        receiveThread.start();

                }  catch  (IOException  e)  {
                        e.printStackTrace();
                }
		
		
	}
	

}

2,客户端代码

import  java.io.IOException;
import  java.net.Socket;
import  java.util.Scanner;

public  class  Client  {
        public  static  void  main(String[]  args)  {
                try  {
                        Socket  socket  =  new  Socket("localhost",  8888);
                        Scanner  scanner  =  new  Scanner(System.in);
                        ClientReceiveThread  receiveThread  =  new  ClientReceiveThread(socket);
                        receiveThread.start();
                        while  (true)  {
                                String  sendMsg  =  scanner.nextLine();
                                ClientSendThread  sendThread  =  new  ClientSendThread(socket,  sendMsg);
                                sendThread.start();
                        }
                }  catch  (IOException  e)  {
                        e.printStackTrace();
                }
        }
}

3,客户端发送和客户端接受代码

import  java.io.IOException;
import  java.io.OutputStream;
import  java.net.Socket;

public  class  ClientSendThread  extends  Thread  {
        private    Socket  socket;
        private    String  sendMsg;

        public  ClientSendThread(Socket  socket,  String  sendMsg)  {
                this.socket  =  socket;
                this.sendMsg  =  sendMsg;
        }

        @Override
        public  void  run()  {
                try  {
                        OutputStream  outputStream  =  socket.getOutputStream();
                        outputStream.write(sendMsg.getBytes());
                        outputStream.flush();
                }  catch  (IOException  e)  {
                        e.printStackTrace();
                }
        }
}
import  java.io.IOException;
import  java.io.InputStream;
import  java.net.Socket;
import  javax.swing.*;
public  class  ClientReceiveThread  extends  Thread  {
        private    Socket  socket;
		JTextArea outputArea;
        public  ClientReceiveThread(Socket  socket,JTextArea outputArea)  {
                this.socket  =  socket;
				this.outputArea=outputArea;
        }

        @Override
        public  void  run()  {
                try  {
                        InputStream  inputStream  =  socket.getInputStream();
                        byte[]  buffer  =  new  byte[1024];
                        int  len;
                        while  ((len  =  inputStream.read(buffer))  !=  -1)  {
                                String  receiveMsg  =  new  String(buffer,  0,  len);
                                outputArea.append("客户端2:"+receiveMsg+"\n");
								
                        }
                }  catch  (IOException  e)  {
                        e.printStackTrace();
                }
        }
}

4,服务器端代码,和服务器端接受信息代码

import  java.io.IOException;
import  java.net.ServerSocket;
import  java.net.Socket;
import  java.util.ArrayList;
import  java.util.List;

public  class  Server  {
        private  static  final  List<Socket>  socketList  =  new  ArrayList<>();
        public  static  void  main(String[]  args)  {
                try  {
                        ServerSocket  serverSocket  =  new  ServerSocket(8888);
                        System.out.println("服务端已启动,等待客户端连接...");
                        while  (true)  {
                                Socket  socket  =  serverSocket.accept();
                                socketList.add(socket);
                                System.out.println("客户端"  +  socket  +  "已连接");
                                ServerReceiveThread  receiveThread  =  new  ServerReceiveThread(socket);
                                receiveThread.start();
                        }
                }  catch  (IOException  e)  {
                        e.printStackTrace();
                }
        }

        public  static  void  sendToOtherClients(Socket  except,  String  msg)  {			//转接信息
                for  (Socket  socket  :  socketList)  {
                        if  (socket  !=  except)  {
                                try  {
                                        socket.getOutputStream().write(msg.getBytes());
                                        socket.getOutputStream().flush();
                                }  catch  (IOException  e)  {
                                        e.printStackTrace();
                                }
                        }
                }
        }
}

import  java.io.IOException;
import  java.io.InputStream;
import  java.net.Socket;

public  class  ServerReceiveThread  extends  Thread  {
        private    Socket  socket;

        public  ServerReceiveThread(Socket  socket)  {
                this.socket  =  socket;
        }

        @Override
        public  void  run()  {
                try  {
                        InputStream  inputStream  =  socket.getInputStream();
                        byte[]  buffer  =  new  byte[1024];
                        int  len;
                        while  ((len  =  inputStream.read(buffer))  !=  -1)  {
                                String  receiveMsg  =  new  String(buffer,  0,  len);
                                System.out.println("收到客户端"  +  socket  +  "的消息:"  +  receiveMsg);
                                Server.sendToOtherClients(socket,  receiveMsg);
                        }
                }  catch  (IOException  e)  {
                        e.printStackTrace();
                }
        }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值