Java实战之基于TCP实现简单聊天程序
作者:howard2005 发布时间:2022-09-01 17:09:20
标签:Java,TCP,聊天
一、如何实现TCP通信
要实现TCP通信需要创建一个服务器端程序和一个客户端程序,为了保证数据传输的安全性,首先需要实现服务器端程序,然后在编写客户端程序。
在本机运行服务器端程序,在远程机运行客户端程序
本机的IP地址:192.168.129.222
远程机的IP地址:192.168.214.213
二、编写C/S架构聊天程序
1.编写服务器端程序 - Server.java
在net.hw.network包里创建Server类
package net.hw.network;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 功能:服务器端
* 作者:华卫
* 日期:2022年03月18日
*/
public class Server extends JFrame {
static final int PORT = 8136;
static final String HOST_IP = "192.168.129.222";
private JPanel panel1, panel2;
private JTextArea txtContent, txtInput, txtInputIP;
private JScrollPane panContent, panInput;
private JButton btnClose, btnSend;
private ServerSocket serverSocket;
private Socket socket;
private DataInputStream netIn;
private DataOutputStream netOut;
public static void main(String[] args) {
new Server();
}
public Server() {
super("服务器");
//创建组件
panel1 = new JPanel();
panel2 = new JPanel();
txtContent = new JTextArea(15, 60);
txtInput = new JTextArea(3, 60);
panContent = new JScrollPane(txtContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panInput = new JScrollPane(txtInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
btnClose = new JButton("关闭");
btnSend = new JButton("发送");
//添加组件
getContentPane().add(panContent, "Center");
getContentPane().add(panel1, "South");
panel1.setLayout(new GridLayout(0, 1));
panel1.add(panInput);
panel1.add(panel2);
panel2.add(btnSend);
panel2.add(btnClose);
//设置组件属性
txtContent.setEditable(false);
txtContent.setFont(new Font("宋体", Font.PLAIN, 13));
txtInput.setFont(new Font("宋体", Font.PLAIN, 15));
txtContent.setLineWrap(true);
txtInput.setLineWrap(true);
txtInput.requestFocus();
setSize(450, 350);
setLocation(50, 200);
setResizable(false);
setVisible(true);
//等候客户请求
try {
txtContent.append("服务器已启动...\n");
serverSocket = new ServerSocket(PORT);
txtContent.append("等待客户请求...\n");
socket = serverSocket.accept();
txtContent.append("连接一个客户。\n" + socket + "\n");
netIn = new DataInputStream(socket.getInputStream());
netOut = new DataOutputStream(socket.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
/
//注册 * ,编写事件代码
txtContent.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
displayClientMsg();
}
});
txtInput.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
displayClientMsg();
}
});
panel2.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
displayClientMsg();
}
});
txtInput.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
displayClientMsg();
}
});
txtInput.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
displayClientMsg();
}
});
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String serverMsg = txtInput.getText();
if (!serverMsg.trim().equals("")) {
txtContent.append("服务器>" + serverMsg + "\n");
netOut.writeUTF(serverMsg);
} else {
JOptionPane.showMessageDialog(null, "不能发送空信息!", "服务器", JOptionPane.WARNING_MESSAGE);
}
txtInput.setText("");
txtInput.requestFocus();
} catch (IOException ie) {
ie.printStackTrace();
}
}
});
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
netIn.close();
netOut.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
netIn.close();
netOut.close();
socket.close();
serverSocket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
System.exit(0);
}
public void windowActivated(WindowEvent e) {
txtInput.requestFocus();
}
});
}
//显示客户端信息
void displayClientMsg() {
try {
if (netIn.available() > 0) {
String clientMsg = netIn.readUTF();
txtContent.append("客户端>" + clientMsg + "\n");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
2.编写客户端程序 - Client.java
在net.hw.network包里创建Client类
package net.hw.network;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
/**
* 功能:客户端
* 作者:华卫
* 日期:2022年03月18日
*/
public class Client extends JFrame {
private JPanel panel1, panel2;
private JTextArea txtContent, txtInput;
private JScrollPane panContent, panInput;
private JButton btnClose, btnSend;
private Socket socket;
private DataInputStream netIn;
private DataOutputStream netOut;
public static void main(String[] args) {
new Client();
}
public Client() {
super("客户端");
//创建组件
panel1 = new JPanel();
panel2 = new JPanel();
txtContent = new JTextArea(15, 60);
txtInput = new JTextArea(3, 60);
panContent = new JScrollPane(txtContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panInput = new JScrollPane(txtInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
btnClose = new JButton("关闭");
btnSend = new JButton("发送");
//添加组件
getContentPane().add(panContent, "Center");
getContentPane().add(panel1, "South");
panel1.setLayout(new GridLayout(0, 1));
panel1.add(panInput);
panel1.add(panel2);
panel2.add(btnSend);
panel2.add(btnClose);
//设置组件属性
txtContent.setEditable(false);
txtContent.setFont(new Font("宋体", Font.PLAIN, 13));
txtInput.setFont(new Font("宋体", Font.PLAIN, 15));
txtContent.setLineWrap(true);
txtInput.setLineWrap(true);
txtInput.requestFocus();
setSize(450, 350);
setLocation(550, 200);
setResizable(false);
setVisible(true);
//连接服务器
try {
txtContent.append("连接服务器...\n");
socket = new Socket(Server.HOST_IP, Server.PORT);
txtContent.append("连接服务器成功。\n" + socket + "\n");
netIn = new DataInputStream(socket.getInputStream());
netOut = new DataOutputStream(socket.getOutputStream());
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "服务器连接失败!\n请先启动服务器程序!", "客户端", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
/
//注册 * ,编写事件代码
txtContent.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
displayServerMsg();
}
});
txtInput.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
displayServerMsg();
}
});
panel2.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
displayServerMsg();
}
});
txtInput.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
displayServerMsg();
}
});
txtInput.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
displayServerMsg();
}
});
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String clientMsg = txtInput.getText();
if (!clientMsg.trim().equals("")) {
netOut.writeUTF(clientMsg);
txtContent.append("客户端>" + clientMsg + "\n");
} else {
JOptionPane.showMessageDialog(null, "不能发送空信息!", "客户端", JOptionPane.WARNING_MESSAGE);
}
txtInput.setText("");
txtInput.requestFocus();
} catch (IOException ie) {
ie.printStackTrace();
}
}
});
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
netIn.close();
netOut.close();
socket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
System.exit(0);
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
netIn.close();
netOut.close();
socket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
System.exit(0);
}
public void windowActivated(WindowEvent e) {
txtInput.requestFocus();
}
});
}
//显示服务端信息
void displayServerMsg() {
try {
if (netIn.available() > 0) {
String serverMsg = netIn.readUTF();
txtContent.append("服务器>" + serverMsg + "\n");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
3.测试服务器端与客户端能否通信
在本机[192.168.129.222]上启动服务器端
在远程机[192.168.214.213]上启动客户端
显示连接服务器[192.168.129.222]成功,切换到服务器端查看,显示连接了一个客户[192.168.214.213]
此时,服务器端和客户端就可以相互通信了
4.程序优化思路 - 服务器端采用多线程
其实,很多服务器端程序都是允许被多个应用程序访问的,例如门户网站可以被多个用户同时访问,因此服务器端都是多线程的。
来源:https://blog.csdn.net/howard2005/article/details/123573139


猜你喜欢
- 先理解一下RFC(Romote Function Call)远程函数调用调用前提:1.要想通过C# 通过RFC调用SAP端,SAP端要存在R
- Android EditText输入手机号空格开发需求是在登录页面的手机EditText中间插入空格,让用户看起来方便点, 130 1234
- 1. 前言Spring最重要的一个概念当属Bean了,我们写的Controller、Service、Dao凡是加了对应注解交给Spring管
- 前言在C/S这种模式中,自动更新程序就显得尤为重要,它不像B/S模式,直接发布到服务器上,浏览器点个刷新就可以了。由于涉及到客户端文件,所以
- 小编今天研究了在Unity3D中的数据持久化问题。数据持久化在任何一个开发领域都是一个值得关注的问题,小到一个应用中配置文件的读写,大到数据
- 一、前期工作创建工作空间 二、创建工作包创建完成后,文件夹的格式为:三、准备编译文件和代码3.1 更换编译文件中的内容将上图中的,
- 功能介绍大家都知道在Spring boot开发过程中,需要在配置文件里配置许多信息,如数据库的连接信息等,如果不加密,传明文,数据库就直接暴
- 一、结论先行ArrayList在JDK1.8与JDK1.7底层区别JDK1.7:ArrayList像饿汉式,直接创建一个初始容量为10的数组
- ThymeleafThymeleaf是最近SpringBoot推荐支持的模板框架,官网在thymeleaf.org这里。我们为什么要用Thy
- 相信大家一定遇到过某些App在手机桌面打开时会出现短暂或者几秒钟的白屏情况吧,没错那是应用程序启动后系统默认的背景色,此时应用的第一个Act
- 在Android开发中,有时候可能会要用到碎纸机的效果,今天小编为大家整理好代码,一起来看看吧。首先来看下效果图实例代码xml<com
- 我的安卓开发经历始于一个原生安卓项目开发。后来由于公司有个项目与几家医疗设备公司合作,需要我写安卓端的桥接代码给 react native
- 概述事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性。Spring Framework对事务管理提供了一致的
- 反阈值二值化反阈值二值化与阈值二值化互为逆操作。在OpenCV中该类的实现依赖于threshold() 函数。下面是该函数的声明:thres
- 本文实例分析了win7中C#的winForm编程使用savefiledialog不能弹出保存窗体的解决方法。分享给大家供大家参考。具体分析如
- Android横竖屏切换时,当前的Activity会被销毁,然后Activity上面的数据将会全部丢失。如Listview上面每个item的
- 基数排序也是桶排序的一种,也是跟样本数据强相关的,且基数排序要求样本数据是非负的十进制数,如果有小数或者负数,那么代码将要大量重写!这就是不
- 用法一:常量在JDK1.5之前,我们定义常量都是:publicstaticfianl....。现在好了,有了枚举,可以把相关的常量分组到一个
- 底座的状态跟充电状态类似,很多底座提供充电功能(座充).底座状态同样使用sticky Intent广播。可以查询设备是否插入底座,哪种底座。
- 相信大家一定都使用过手机QQ和微信之类的软件,当我们使用时不难发现其界面的切换不仅可以通过点击页标签来实现,还可以通过左右滑动来实现的,耗子