当前位置:网站首页>简单的聊天室系统Socket实现
简单的聊天室系统Socket实现
2022-06-09 11:48:00 【3550272599】
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();
}
}边栏推荐
- The virtual machine appears in entering emergency mode, and XFS is used_ Rapair device or resource busy solution
- [译]PostgreSQL 怎么通过vacuum 加速事务ID回收的速度
- 『忘了再学』Shell基础 — 28、AWK中条件表达式说明
- 5.<tag-回溯和切割问题>lt.93.复原IP地址
- 期货开户云,开户可靠安全吗??
- 6. exchange the nodes in the linked list in pairs
- 企评家用杜邦分析法剖析:华东建筑集团股份有限公司企业财务状况
- Excel | App_WorkbookActive中存在错误不能设置类 Addin 的Installed属性
- 13. Using WPF to develop USB detection tool
- Gson, fastjason, Jackson serialization differences
猜你喜欢

Tag greedy - brush questions to prepare knowledge - greedy problem solving methods + lt.455 Distribute cookies + lt.376 Wobble sequence

ThreadPoolExecutor from mastery to entry

Endnote | how to quickly share literature with others (including title + Notes +pdf file) | endnote save backup

6. < tag backtracking and cutting problems > lt.131 Split palindrome string

Excel | App_WorkbookActive中存在错误不能设置类 Addin 的Installed属性

8.<tag-回溯和全排列>lt.46. 全排列 + lt.47. 全排列 II

06 | the first step of China Taiwan landing: enterprise strategy decomposition and current situation research (Discovery)

SIGIR 2022 | CMI: micro video recommendation combining comparative learning and multi interest mining

13. Using WPF to develop USB detection tool

Do you dare to deliver your microservices independently?
随机推荐
Do you dare to deliver your microservices independently?
【堆排|快排】Top-k问题
Will investment and wealth management products lose the principal?
[untitled]
死锁的排查工具有哪些?
请你说说乐观锁和悲观锁,以及适用场景
『忘了再学』Shell基础 — 28、AWK中条件表达式说明
BFS练手题目
实验室常用工具 | 实验溶液配制 | 摩尔浓度及分子量计算工具 molarity-calculator
Range method returns the object conversion method
爱可可AI前沿推介(6.9)
Gson, fastjason, Jackson serialization differences
07 | the second step of the mid platform landing: enterprise digital panoramic planning (define)
10. < tag binary tree and BST foundation > lt.700 Search in binary search tree + lt.98 Validate binary search tree + lt.530 Minimum absolute difference of binary search tree (the same as lt.783)
Zotero | Literature Association
[转载] 分布式系统的“脑裂”到底是个什么玩意?
企评家用杜邦分析法剖析:华东建筑集团股份有限公司企业财务状况
GameFi新的启程,AQUANEE将于6.9日登陆Gate以及BitMart
curator - 实现服务注册与发现
Rédaction de documents scientifiques