简单的聊天室系统Socket实现

这是一个使用Java实现的简单聊天应用,包括客户端和服务器端。客户端通过Socket连接服务器,建立输入输出流,实现消息的发送和接收。服务器端开启监听,接受客户端连接,同样通过输入输出流进行通信。应用支持多轮聊天直到服务器端终止连接。

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

package cn.dom;

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

//客户端
public class ClientChat extends JFrame implements ActionListener{
	private JButton btnSend;//发送按钮
	private JTextArea jtaRecord;//聊天记录
	private JTextField jtfMessage;//消息框
	
	private ObjectOutputStream out;//输出流对象
	private ObjectInputStream in;//输入流对象
	
	private String msg="";
	private String chatSerer;
	private Socket client;

	public ClientChat() {
		super("客户端");
		setSize(400,320);
		setLocation(100,100);
		setResizable(false);
		Container container=getContentPane();
		
		JPanel pnlTop=new JPanel();
		pnlTop.setLayout(new FlowLayout(FlowLayout.LEFT));
		container.add(pnlTop,BorderLayout.NORTH);
		JPanel pnlRecord=new JPanel();
		pnlTop.add(new JLabel("聊天内容:"));
		pnlTop.add(pnlRecord);
		
		jtaRecord=new JTextArea(12,30);
		jtaRecord.setEditable(false);
		jtaRecord.setLineWrap(true);
		pnlRecord.add(jtaRecord);
		JScrollPane scroll=new JScrollPane(jtaRecord);
		scroll.setSize(336,113);
		pnlRecord.add(scroll);
		
		JPanel pnlBottom=new JPanel();
		pnlBottom.setLayout(new FlowLayout(FlowLayout.LEFT));
		container.add(pnlBottom,BorderLayout.SOUTH);
		pnlBottom.add(new JLabel("消息"));
		jtfMessage=new JTextField(25);
		pnlBottom.add(jtfMessage);
		btnSend=new JButton("发送");
		pnlBottom.add(btnSend);
		btnSend.addActionListener(this);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	
	
//启动客户端
	public void runClient() {
		try {
			connectServer();
			getStream();
			communication();
		}catch(EOFException e) {
			System.out.println("服务器中止了连接!!!");
		}catch(IOException e)
		{
			e.printStackTrace();
		}finally {
			closeConnection();
		}
	}
	
private void connectServer() throws IOException{
	displayMessage("正在尝试连接....\n");
	client=new Socket(InetAddress.getByName(chatSerer),9999);
	displayMessage("已连接到:"+client.getInetAddress().getHostName()+"\n");
}


//读取流信息
private void getStream() throws IOException{
	out=new ObjectOutputStream(client.getOutputStream());
	out.flush();
	in=new ObjectInputStream(client.getInputStream());
}
//连接成功进行聊天
private void communication() throws IOException{
	setTextFieldEditable(true);
	do {
		try {
			msg=(String) in.readObject();
			displayMessage("\n"+msg);
		}catch(ClassNotFoundException e){
			displayMessage("\n收到异常对象类型!\n");
		}
	}while(!msg.equals("服务器:stop"));
}
//关闭连接
private void closeConnection()
{
	displayMessage("\n关闭连接!!!\n");
	setTextFieldEditable(false);
	try {
		out.close();
		in.close();
		client.close();
	}catch(IOException e)
	{
		e.printStackTrace();
	}
}
//发送数据
private void sendData(String msg) {
	try {
		out.writeObject("客户端:"+msg);
		out.flush();
		displayMessage("\n客户端:"+msg);
	}catch(IOException e) {
		jtaRecord.append("\n发生写入错误!!!");
	}
}

//显示消息
private void displayMessage(final String msg) {
	SwingUtilities.invokeLater(new Runnable()
	{
		public void run() {
			jtaRecord.append(msg);
			jtaRecord.setCaretPosition(jtaRecord.getText().length());
		}
	});
}
//设置文本框状态
private void setTextFieldEditable(final boolean editable) {
	SwingUtilities.invokeLater(new Runnable() {
	public void run()
	{
	jtfMessage.setEditable(editable);
	}
	});
	}
@ Override
public void actionPerformed(ActionEvent event) {
	sendData(jtfMessage.getText());
	 String label=event.getActionCommand();
     switch (label) {
         case "发送":
        	 jtfMessage.setText("");
             break;
     }
}


public static void main(String[] args) {
	new ClientChat().runClient();
}
}

服务端

package cn.dom;


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

public class ServerChat extends JFrame implements ActionListener{
private JButton btnSend;
private JTextArea jtaRecord;
private JTextField jtfMessage;

private ObjectOutputStream out;//输出流对象
private ObjectInputStream in;//输入流对象

private String msg="";
private Socket connect;
private ServerSocket server;
private int count;

public  ServerChat() {
	super("服务器端");
	Container container=getContentPane();;
	setSize(400,320);
	setLocation(100,100);
	setResizable(false);

	JPanel pnlTop=new JPanel();
	pnlTop.setLayout(new FlowLayout(FlowLayout.LEFT));
	container.add(pnlTop,BorderLayout.NORTH);
	JPanel pnlRecord=new JPanel();
	pnlTop.add(new JLabel("聊天内容"));
	pnlTop.add(pnlRecord);
	
	jtaRecord=new JTextArea(12,30);
	jtaRecord.setEditable(false);
	jtaRecord.setLineWrap(true);
	pnlRecord.add(jtaRecord);
	JScrollPane scroll=new JScrollPane(jtaRecord);
	scroll.setSize(336,113);
	pnlRecord.add(scroll);
	
	JPanel pnlBottom=new JPanel();
	pnlBottom.setLayout(new FlowLayout(FlowLayout.LEFT));
	container.add(pnlBottom,BorderLayout.SOUTH);
	pnlBottom.add(new JLabel("消息"));
	jtfMessage=new JTextField(25);
	pnlBottom.add(jtfMessage);
	btnSend=new JButton("发送");
	pnlBottom.add(btnSend);
	btnSend.addActionListener(this);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setVisible(true);
}

//运行服务器
public void runServer()
{
	try {
		server=new ServerSocket(9999);
		while(true)
		{
			try {
				listenConnection();
				getStream();
				communication();
			}catch(EOFException e){
				System.err.println("服务器终止了连接!!!");
			}finally {
				closeConnection();
				count++;
			}
		}
	}catch(IOException e) {
		e.printStackTrace();
	}
}

//发送数据
private void sendData(String msg) {
	try {
		out.writeObject("服务端:"+msg);
		out.flush();
		displayMessage("\n服务端:"+msg);
	}catch(IOException e) {
		jtaRecord.append("\n发生写入错误!!!");
	}
}


//显示消息
private void displayMessage(final String msg) {
	SwingUtilities.invokeLater(new Runnable()
	{
		public void run() {
			jtaRecord.append(msg);
			jtaRecord.setCaretPosition(jtaRecord.getText().length());
		}
	});
}
//读取流信息

private void getStream() throws IOException{
	out=new ObjectOutputStream(connect.getOutputStream());
	out.flush();
	in=new ObjectInputStream(connect.getInputStream());
}

//连接成功进行聊天
private void communication() throws IOException{
	setTextFieldEditable(true);
	do {
		try {
			msg=(String) in.readObject();
			displayMessage("\n"+msg);
		}catch(ClassNotFoundException e){
			displayMessage("\n收到异常对象类型!\n");
		}
	}while(!msg.equals("服务器:stop"));
}

//监听连接
private void listenConnection() throws IOException{
	displayMessage("服务器已启动等待连接.....\n");
	connect=server.accept();
	displayMessage("收到连接"+count+"从"+connect.getInetAddress().getHostName()+"\n");
}


//关闭连接
private void closeConnection()
{
	displayMessage("\n关闭连接!!!\n");
	setTextFieldEditable(false);
	try {
		out.close();
		in.close();
		server.close();
		connect.close();
	}catch(IOException e)
	{
		e.printStackTrace();
	}
}


//设置文本框状态
private void setTextFieldEditable(final boolean editable) {
	SwingUtilities.invokeLater(new Runnable() {
	public void run()
	{
	jtfMessage.setEditable(editable);
	}
	});
	}

@Override
public void actionPerformed(ActionEvent event) {
	sendData(jtfMessage.getText());
	String label=event.getActionCommand();
    switch (label) {
        case "发送":
       	 jtfMessage.setText("");
            break;
    }
}

public static void main(String[] args) {
	new ServerChat().runServer();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值