Java 服务端、客户端(间)文字交流(含图形用户界面)

本文描述了一个简单的多客户端与服务端通信系统,客户端代码相似,服务端负责接收和转发信息,无论客户端启动顺序。连接成功时有提示,信息在所有连接的客户端间共享。

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

目录

效果

1、服务的界面

2、服务端

3、客户端界面

4、客户端1

5、客户端2


效果

822290d19edb4d39ba6978564f1e87c6.png

两个客户端和一个服务端。

连接成功时有提示信息。

任意一个客户端发送的信息都会被服务端接收并经服务端发送给其他的客户端;而服务端自己发送的信息所有客户端都能接收到。

先运行服务端,再运行(先后无要求)客户端1和2。

多线程:java 客户端、服务端 文字交流 (多线程)-CSDN博客

1、服务的界面

package TPC_6;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

 public  class ServerDemo extends JFrame{//服务端窗口
	private JPanel contentPane;
	public JTextArea textField ;//内容区
	private JScrollPane scrollPane ;//滚轮
	public JTextField textField_1;//输入区
	public JButton button = new JButton("发   送");//监听器在服务端类添加、实现
	public JButton btnNewButton = new JButton("清   除");
	private boolean flag=false;
	
		public  ServerDemo() {//构造,初始化
		setTitle("服务端-聊天室");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel label_1 = new JLabel("聊天内容:");
		label_1.setBounds(30, 10, 80, 15);
		contentPane.add(label_1);
		
		scrollPane = new JScrollPane();
		scrollPane.setBounds(30, 37, 376, 144);
        contentPane.add(scrollPane);
        
        textField = new JTextArea();
		textField.setBounds(30, 37, 376, 144);
		textField.setEditable(false);
		scrollPane.setViewportView(textField);

		JLabel label = new JLabel("请输入您要发送的消息:");
		label.setBounds(30, 191, 146, 15);
		contentPane.add(label);
		
		textField_1 = new JTextField();
		textField_1.setBounds(172, 188, 221, 21);
		contentPane.add(textField_1);
		textField_1.setColumns(10);

		button.setBounds(242, 228, 93, 23);
		contentPane.add(button);
		
		btnNewButton.setBounds(66, 228, 93, 23);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textField_1.setText("");
			}
		});
		contentPane.add(btnNewButton);
	}
	public JTextArea get() {
		return this.textField;
	}
	public JTextField get_1() {
		return this.textField_1;
	}
	public boolean getFlag() {
		return this.flag;
	}
	public void revise() {
		this.flag=false;
	}

}

2、服务端

package TPC_6;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server0 extends Thread{//服务端
    private ServerDemo serverFrame;
		DataOutputStream out1,out2;
		ServerSocket serverSocket1=null;
		Socket clientSocket1=null;
		ServerSocket serverSocket2=null;
		Socket clientSocket2=null;
		DataInputStream in1,in2;
	public void run() {
		try {
		serverFrame = new ServerDemo();
		serverFrame.setVisible(true);
			serverSocket1=new ServerSocket(60001);
			serverSocket2=new ServerSocket(60002);
			serverFrame.button.addActionListener(new ActionListener() {//为“发   送”按钮添加监听器
				public void actionPerformed(ActionEvent e) {	
					if(serverFrame.textField_1.getText().equals("")==false) {//输入不为空
						//输出格式:时间\n谁输出        内容
						if(serverFrame.textField.getText()!=null) {
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
							Date date = new Date();		
							String s = simpleDateFormat.format(date);
							serverFrame.textField.setText(serverFrame.textField.getText()+s+"\r\n"
							+"服务端:      "+serverFrame.textField_1.getText()+"\r\n");
						}	
						else {
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
							Date date = new Date();		
							String s = simpleDateFormat.format(date);
							serverFrame.textField.setText(s+"\r\n"+"服务端:      "+serverFrame.textField_1.getText()+"\r\n");
						}
						try{//输出客户端1、2
							out1.writeUTF("服务端:      "+serverFrame.textField_1.getText());//服务端-->客户端1------------------------------------
							out2.writeUTF("服务端:      "+serverFrame.textField_1.getText());//服务端-->客户端2------------------------------------
						}catch (Exception exception) {
							System.out.println(exception.getMessage());
						}
						serverFrame.textField_1.setText("");
					}
				}
			});
			//为每个客户端创建线程
			//客户端1线程th1
			Thread th1=new Thread(new Runnable() {
				public void run() {
					String str1=null;
					try {//等待连接客户端1
				    	clientSocket1=serverSocket1.accept();
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						Date date = new Date();		
						String s = simpleDateFormat.format(date);
						serverFrame.textField.append(s+"\r\n"+"Client1连接成功,开始聊天吧!"+"\r\n");
					 out1=new DataOutputStream(clientSocket1.getOutputStream());
							out1.writeUTF("连接成功!");
							 in1=new DataInputStream(clientSocket1.getInputStream());
						} catch (IOException e) {
							e.printStackTrace();
						}
					while(true) {//开始聊天
				try {
					str1=in1.readUTF();
					out2.writeUTF("客户端1:      "+str1);//客户端1-->客户端2------------------------------------
		    		if(str1.equals("")==false) {//消息不为空
					//输出格式:时间\n谁输出        内容
					if(serverFrame.textField.getText()!=null) {
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						Date date = new Date();		
						String s = simpleDateFormat.format(date);
						serverFrame.textField.setText(serverFrame.textField.getText()+s+"\r\n"+"客户端1:      "+str1+"\r\n");
					}	
					else {
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						Date date = new Date();		
						String s = simpleDateFormat.format(date);
						serverFrame.textField.setText(s+"\r\n"+"客户端1:      "+str1+"\n");
					}
				}
				} catch (IOException e) {
					e.printStackTrace();
				} 
				 }
				}
			});
			//客户端2线程th2
			Thread th2=new Thread(new Runnable() {
				public void run() {
				try {
			    	clientSocket2=serverSocket2.accept();
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
					Date date = new Date();		
					String s = simpleDateFormat.format(date);
					serverFrame.textField.append(s+"\r\n"+"Client2连接成功,开始聊天吧!"+"\r\n");
			 out2=new DataOutputStream(clientSocket2.getOutputStream());
					out2.writeUTF("连接成功!");
					 in2=new DataInputStream(clientSocket2.getInputStream());
				} catch (IOException e) {
					e.printStackTrace();
				}
			String str2=null;
			while(true) {
		try {
			str2=in2.readUTF();
			out1.writeUTF("客户端2:      "+str2);//客户端2-->客户端1------------------------------------
		if(str2.equals("")==false) {//消息不为空
			//输出格式:时间\n谁输出        内容
			if(serverFrame.textField.getText()!=null) {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
				Date date = new Date();		
				String s = simpleDateFormat.format(date);
				serverFrame.textField.setText(serverFrame.textField.getText()+s+"\r\n"+"客户端2:      "+str2+"\r\n");
			}	
			else {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
				Date date = new Date();		
				String s = simpleDateFormat.format(date);
				serverFrame.textField.setText(s+"\r\n"+"客户端2:      "+str2+"\n");
			}
		}
		} catch (IOException e) {
			e.printStackTrace();
		}
			}
				}
			});//线程th1、th2创建完成
			th1.start();//启动线程
           th2.start();
		}catch (Exception exception) {
			System.out.println(exception.getMessage());
		}
	}
	public static void main(String[] args) {
		Server0 server=new Server0();
		server.start();
	}
	
}

3、客户端界面

package TPC_6;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ClientDemo extends JFrame {
	private JPanel contentPane;
	public JTextArea textField ;//内容区
	private JScrollPane scrollPane ;//滚轮
	public JTextField textField_1;//输入区
	public JButton button = new JButton("发   送");//监听器在客户端类添加、实现
	public JButton button_1 = new JButton("清   除");
	private boolean flag=false;
	
	public  ClientDemo(int num) {//构造,初始化
		setTitle("客户端"+num+"-聊天室");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel label = new JLabel("对话内容:");
		label.setBounds(26, 10, 69, 15);
		contentPane.add(label);
		
		scrollPane = new JScrollPane();
		scrollPane.setBounds(26, 30, 379, 142);
        contentPane.add(scrollPane);
		
        textField = new JTextArea();
		textField.setBounds(26, 30, 379, 142);
		textField.setEditable(false);
		scrollPane.setViewportView(textField);
		
		JLabel label_1 = new JLabel("请输入你要发送的消息:");
		label_1.setBounds(26, 192, 149, 21);
		contentPane.add(label_1);
		
		textField_1 = new JTextField();
		textField_1.setBounds(185, 192, 193, 21);
		contentPane.add(textField_1);
		textField_1.setColumns(10);
		
		button.setBounds( 242,228,93, 23);
		contentPane.add(button);
		
		button_1.setBounds(66, 228, 93, 23);
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textField_1.setText("");
			}
		});
		contentPane.add(button_1);
	}
	public JTextArea get() {
		return this.textField;
	}
	public JTextField get_1() {
		return this.textField_1;
	}
	public boolean getFlag() {
		return this.flag;
	}
	public void revise() {
		this.flag=false;
	}
}

4、客户端1

package TPC_6;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
public class Client1 extends Thread{//客户端1
       public ClientDemo clientFrame1;
       
	public void run() {
		Socket cilent=null;
		String fromServer=null;//获取内容
		clientFrame1=new ClientDemo(1);
		clientFrame1.setVisible(true);
		try {
			cilent=new Socket("127.0.0.1",60001);
			DataOutputStream out=new DataOutputStream(cilent.getOutputStream());
			DataInputStream in=new DataInputStream(cilent.getInputStream());
			clientFrame1.button.addActionListener(new ActionListener() {//为“发  送”按钮添加监听器
				public void actionPerformed(ActionEvent e) {
					if(clientFrame1.textField_1.getText().equals("")==false) {//输入不为空
						//输出格式:时间\n谁输出        内容
						if(clientFrame1.textField.getText()!=null) {
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
							Date date = new Date();		
							String s = simpleDateFormat.format(date);
							clientFrame1.textField.setText(clientFrame1.textField.getText()+s+"\r\n"
							+"自己(客户端1):      "+clientFrame1.textField_1.getText()+"\r\n");
						}
						else {
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
							Date date = new Date();		
							String s = simpleDateFormat.format(date);
							clientFrame1.textField.setText(s+"\r\n"+"自己(客户端1):      "+clientFrame1.textField_1.getText()+"\r\n");
						}
						try{//输出给服务端
							out.writeUTF(clientFrame1.textField_1.getText());
						}catch (Exception exception) {
							System.out.println(exception.getMessage());
						}
						clientFrame1.textField_1.setText("");
					}	
				}
			});
			while(true) {//不断获取消息
				fromServer=in.readUTF();
				if(fromServer.equals("")==false) 
				{
					if(fromServer.equals("Client1连接成功,开始聊天吧!")==true) {//刚连接成功
						clientFrame1.textField.setText("连接成功!"+"\r\n");
						System.out.print("1-");
					}
					else {
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						Date date = new Date();		
						String s = simpleDateFormat.format(date);
						clientFrame1.textField.setText(clientFrame1.textField.getText()+s+"\r\n"+fromServer+"\r\n");
						System.out.print("1+");
					}
						
				}	
			}
		}catch(Exception exception) {
			System.out.println(exception.getMessage());
		}		
	}
	public static void main(String[] args) {
		Client1 client1=new Client1();
		client1.start();
	}	
	
}

5、客户端2

package TPC_6;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
public class Client2 extends Thread{//客户端2
        public ClientDemo clientFrame2;
        
	public void run() {
		 Socket client=null;
		 String fromServer=null;//获取内容
		clientFrame2=new ClientDemo(2);
		clientFrame2.setVisible(true);
		try {
			client=new Socket("127.0.0.2",60002);
			DataOutputStream out=new DataOutputStream(client.getOutputStream());
			DataInputStream in=new DataInputStream(client.getInputStream());
			clientFrame2.button.addActionListener(new ActionListener() {//为“发  送”按钮添加监听器
				public void actionPerformed(ActionEvent e) {
					if(clientFrame2.textField_1.getText().equals("")==false) {//输入不为空
						//输出格式:时间\n谁输出        内容
						if(clientFrame2.textField.getText()!=null) {
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
							Date date = new Date();		
							String s = simpleDateFormat.format(date);
							clientFrame2.textField.setText(clientFrame2.textField.getText()+s+"\r\n"
							+"自己(客户端2):      "+clientFrame2.textField_1.getText()+"\r\n");
						}
						else {
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
							Date date = new Date();		
							String s = simpleDateFormat.format(date);
							clientFrame2.textField.setText(s+"\r\n"+"自己(客户端2):      "+clientFrame2.textField_1.getText()+"\r\n");
						}
						try{//输出给服务端
							out.writeUTF(clientFrame2.textField_1.getText());
						}catch (Exception exception) {
							System.out.println(exception.getMessage());
						}
						clientFrame2.textField_1.setText("");
					}	
				}
			});
			while(true) {//不断获取消息
				fromServer=in.readUTF();
				if(fromServer.equals("")==false) 
				{
					if(fromServer.equals("Client2连接成功,开始聊天吧!")==true) {//刚连接成功
						clientFrame2.textField.setText("连接成功!"+"\r\n");
				    	System.out.print("2-");
					}
					else {
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						Date date = new Date();		
						String s = simpleDateFormat.format(date);
						clientFrame2.textField.setText(clientFrame2.textField.getText()+s+"\r\n"+fromServer+"\r\n");
						System.out.print("2+");
					}
						
				}	
			}
		}catch(Exception exception) {
			System.out.println(exception.getMessage());
		}		
	}
	public static void main(String[] args) {
		Client2 client2=new Client2();
		client2.start();
	}	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草海桐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值