Java聊天室之使用Socket实现传递对象
作者:小虚竹and掘金 时间:2023-02-07 15:28:52
一、题目描述
题目实现:使用网络编程时,需要通过Socket传递对象。
二、解题思路
创建一个类:Student,实现序列化
Student类包含两个属性及对应的get()和set()方法
创建一个服务器类:ServerSocketFrame,继承JFrame类
写一个getserver() 方法,实例化Socket对象,启用9527当服务的端口。
创建输入流对象,用来接收客户端信息。
再定义一个getClientInfo()方法,用于接收客户端发送的信息。
对文本框添加一个事件:实现向客户端发磅信息。
创建一个客户端类:ClientSocketFrame,继承JFrame类。
写一个connect() 方法,实例化Socket对象,连接本地服务的9527端口服务。
再定义一个getClientInfo()方法,用于接收服务端发送的信息。
技术重点:
在Java中使用Socket传递对象时,该对象必须是序列化的,在Java中实现Serializable接口的类,创建的对象就是序列化对象,可以通过Socket进行传递,从而实现了使用Socket传递对象的功能。 Serializable接口在javaio包中,该接口没有方法,只是用于标识对象是可序列化的。该接口的定义如下: public interface Serializable 使用Serializable接口,可以创建序列化类。
三、代码详解
Student
package com.xiaoxuzhu;
import java.io.Serializable;
/**
* Description:
*
* @author xiaoxuzhu
* @version 1.0
*
* <pre>
* 修改记录:
* 修改后版本 修改人修改日期修改内容
* 2022/6/4.1 xiaoxuzhu2022/6/4 Create
* </pre>
* @date 2022/6/4
*/
public class Student implements Serializable { // 序列化对象类
private String id; // 类的成员变量
private String name;// 类的成员变量
public String getId() { // 成员变量的getter方法
return id;
}
public void setId(String id) {// 成员变量的setter方法
this.id = id;
}
public String getName() {// 成员变量的getter方法
return name;
}
public void setName(String name) {// 成员变量的setter方法
this.name = name;
}
}
ServerSocketFrame
package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* Description:
*
* @author xiaoxuzhu
* @version 1.0
*
* <pre>
* 修改记录:
* 修改后版本 修改人修改日期修改内容
* 2022/6/4.1 xiaoxuzhu2022/6/4 Create
* </pre>
* @date 2022/6/4
*/
public class ServerSocketFrame extends JFrame {
private JTextField tf_name;
private JTextField tf_id;
private JTextArea ta_info;
private ObjectOutputStream out = null; // 创建流对象
private ObjectInputStream in = null; // 创建流对象
private ServerSocket server; // 声明ServerSocket对象
private Socket socket; // 声明Socket对象socket
public void getserver() {
try {
server = new ServerSocket(9527); // 实例化Socket对象
ta_info.append("服务器套接字已经创建成功\n"); // 输出信息
while (true) { // 如果套接字是连接状态
ta_info.append("等待客户机的连接......\n"); // 输出信息
socket = server.accept(); // 实例化Socket对象
ta_info.append("客户机连接成功\n"); // 输出信息
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
getClientInfo(); // 调用getClientInfo()方法
}
} catch (Exception e) {
e.printStackTrace(); // 输出异常信息
}
}
private void getClientInfo() {
try {
while (true) { // 如果套接字是连接状态
Student stud = (Student)in.readObject();
if (stud!=null)
ta_info.append("接收到客户机发送的 编号为:" + stud.getId() + " 名称为:" +stud.getName() + "\n"); // 获得客户端信息
}
} catch (Exception e) {
ta_info.append("客户端已退出。\n"); // 输出异常信息
} finally {
try {
if (in != null) {
in.close();// 关闭流
}
if (socket != null) {
socket.close(); // 关闭套接字
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) { // 主方法
ServerSocketFrame frame = new ServerSocketFrame(); // 创建本类对象
frame.setVisible(true);
frame.getserver(); // 调用方法
}
public ServerSocketFrame() {
super();
setTitle("服务器端程序");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 379, 260);
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
ta_info = new JTextArea();
scrollPane.setViewportView(ta_info);
final JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
final JLabel label = new JLabel();
label.setText("编号:");
panel.add(label);
tf_id = new JTextField();
tf_id.setPreferredSize(new Dimension(70,25));
panel.add(tf_id);
final JLabel label_1 = new JLabel();
label_1.setText("名称:");
panel.add(label_1);
tf_name = new JTextField();
tf_name.setPreferredSize(new Dimension(100,25));
panel.add(tf_name);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Student stud = new Student();
stud.setId(tf_id.getText());
stud.setName(tf_name.getText());
try {
out.writeObject(stud);
} catch (IOException e1) {
e1.printStackTrace();
}
ta_info.append("服务器发送的 编号是:" + tf_id.getText() + " 名称是:"+tf_name.getText()+"\n"); // 将文本框中信息显示在文本域中
tf_id.setText(null); // 将文本框清空
tf_name.setText(null);
}
});
button.setText("发 送");
panel.add(button);
}
}
ClientSocketFrame
package com.xiaoxuzhu;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
/**
* Description:
*
* @author xiaoxuzhu
* @version 1.0
*
* <pre>
* 修改记录:
* 修改后版本 修改人修改日期修改内容
* 2022/6/4.1 xiaoxuzhu2022/6/4 Create
* </pre>
* @date 2022/6/4
*/
public class ClientSocketFrame extends JFrame { // 创建类继承JFrame类
private JButton button;
private JTextField tf_name;
private JLabel label_1;
private JLabel label;
private JPanel panel;
private ObjectInputStream in = null;// 创建流对象
private ObjectOutputStream out = null;// 创建流对象
private Socket socket;// 声明Socket对象
private JTextArea ta_info = new JTextArea();// 创建JtextArea对象
private JTextField tf_id = new JTextField();// 创建JtextField对象
private Container cc;// 声明Container对象
public ClientSocketFrame() { // 构造方法
super(); // 调用父类的构造方法
setTitle("客户端程序");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 373, 257);
cc = this.getContentPane(); // 实例化对象
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(ta_info);
getContentPane().add(getPanel(), BorderLayout.NORTH);
}
private void connect() { // 连接套接字方法
ta_info.append("尝试连接......\n"); // 文本域中信息信息
try { // 捕捉异常
socket = new Socket("127.0.0.1", 9527); // 实例化Socket对象
while (true){
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
ta_info.append("完成连接。\n"); // 文本域中提示信息
getClientInfo();
}
} catch (Exception e) {
e.printStackTrace(); // 输出异常信息
}
}
public static void main(String[] args) { // 主方法
ClientSocketFrame clien = new ClientSocketFrame(); // 创建本例对象
clien.setVisible(true); // 将窗体显示
clien.connect(); // 调用连接方法
}
private void getClientInfo() {
try {
while (true) { // 如果套接字是连接状态
Student stud = (Student)in.readObject();
if (stud!=null)
ta_info.append("接收到服务器发送的 编号为:" + stud.getId() + " 名称为:" +stud.getName() + "\n"); // 获得服务器信息
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();// 关闭流
}
if (socket != null) {
socket.close(); // 关闭套接字
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @return
*/
protected JPanel getPanel() {
if (panel == null) {
panel = new JPanel();
panel.add(getLabel());
tf_id.setPreferredSize(new Dimension(70, 25));
panel.add(tf_id);
panel.add(getLabel_1());
panel.add(getTf_name());
panel.add(getButton());
}
return panel;
}
/**
* @return
*/
protected JLabel getLabel() {
if (label == null) {
label = new JLabel();
label.setText("编号:");
}
return label;
}
/**
* @return
*/
protected JLabel getLabel_1() {
if (label_1 == null) {
label_1 = new JLabel();
label_1.setText("名称:");
}
return label_1;
}
/**
* @return
*/
protected JTextField getTf_name() {
if (tf_name == null) {
tf_name = new JTextField();
tf_name.setPreferredSize(new Dimension(100, 25));
}
return tf_name;
}
/**
* @return
*/
protected JButton getButton() {
if (button == null) {
button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Student stud = new Student();
stud.setId(tf_id.getText());
stud.setName(tf_name.getText());
try {
out.writeObject(stud);
} catch (IOException e1) {
e1.printStackTrace();
}
ta_info.append("客户端发送的 编号是:" + tf_id.getText() + " 名称是:"+tf_name.getText()+"\n"); // 将文本框中信息显示在文本域中
tf_id.setText(null); // 将文本框清空
tf_name.setText(null);
}
});
button.setText("发 送");
}
return button;
}
}
服务器启动
客户端连接
服务器发送学生信息
客户端接收学生信息
客户端发送学生信息
服务端接收学生信息
来源:https://juejin.cn/post/7156811403389567006
标签:Java,聊天室,Socket,传递对象
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
android实现简单拼图游戏
2021-11-17 09:28:23
![](https://img.aspxhome.com/file/2023/9/95969_0s.jpg)
C#线程定义和使用方法详解
2022-08-18 00:51:51
![](https://img.aspxhome.com/file/2023/4/77264_0s.jpg)
Spring Boot mybatis-config 和 log4j 输出sql 日志的方式
2021-05-31 22:13:20
![](https://img.aspxhome.com/file/2023/6/101756_0s.png)
关于MyBatis模糊查询的几种实现方式
2023-05-09 04:23:12
SpringBoot 使用Prometheus采集自定义指标数据的方案
2023-04-25 02:50:39
![](https://img.aspxhome.com/file/2023/4/75494_0s.jpg)
安卓版微信小程序跳一跳辅助
2022-08-30 13:44:20
![](https://img.aspxhome.com/file/2023/4/109194_0s.jpg)
IDEA调试技巧条件断点实现步骤详解
2023-11-24 16:02:42
![](https://img.aspxhome.com/file/2023/1/70501_0s.png)
java环境变量path和classpath的配置
2023-08-31 01:09:04
![](https://img.aspxhome.com/file/2023/5/58205_0s.jpg)
Java中transient关键字的详细总结
2021-12-11 03:19:33
![](https://img.aspxhome.com/file/2023/2/126352_0s.png)
一种类似JAVA线程池的C++线程池实现方法
2021-11-02 21:31:52
![](https://img.aspxhome.com/file/2023/7/79917_0s.png)
springboot logback调整mybatis日志级别无效的解决
2023-05-03 05:36:21
用代码更新你的jar包
2023-09-19 23:01:04
Android控件之RatingBar自定义星级评分样式
2023-12-22 16:03:33
![](https://img.aspxhome.com/file/2023/3/93303_0s.png)
C# 泛型字典 Dictionary的使用详解
2022-01-19 23:48:17
![](https://img.aspxhome.com/file/2023/8/102258_0s.png)
C#异步调用实例小结
2023-07-16 10:31:03
Java通过JavaMail发送邮件功能
2022-09-07 16:47:20
![](https://img.aspxhome.com/file/2023/1/122291_0s.jpg)
基于私钥加密公钥解密的RSA算法C#实现方法
2022-12-01 07:52:37
Android实现照片墙效果的实例代码
2023-01-20 16:53:37
![](https://img.aspxhome.com/file/2023/3/113313_0s.gif)
详解SpringBoot的事务管理
2022-01-15 13:39:26
![](https://img.aspxhome.com/file/2023/0/74750_0s.png)
C#集合之并发集合的用法
2023-12-24 09:30:21
![](https://img.aspxhome.com/file/2023/8/106498_0s.jpg)