java案例:基于tcp的简单聊天程序(代码片段)

howard2005 howard2005     2023-03-09     531

关键词:

文章目录

一、如何实现TCP通信

  • 要实现TCP通信需要创建一个服务器端程序和一个客户端程序,为了保证数据传输的安全性,首先需要实现服务器端程序,然后在编写客户端程序。
  • 在本机运行服务器端程序,在远程机运行客户端程序
  • 本机的IP地址:192.168.129.222
  • 远程机的IP地址:192.168.214.213

二、编写C/S架构聊天程序

(一)编写服务器端程序 - 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();
        
    

(二)编写客户端程序 - 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 查看详情  

利用java的socket实现一个简单hello/hi聊天程序(代码片段)

 利用java的Socket实现一个简单hello/hi聊天程序 首先,我们来用java实现一个简单的hello/hi聊天程序。在这个程序里,我学习到了怎么用socket套接套接字来进行编程。简单理解了一些关于socket套接字和底层调用的关系。关于jav... 查看详情

java网络编程基础—基于tcp的nio简单聊天系统

在Java网络编程基础(四)中提到了基于Socket的TCP/IP简单聊天系统实现了一个多客户端之间护法消息的简单聊天系统。其服务端采用了多线程来处理多个客户端的消息发送,并转发给目的用户。但是由于它是基于Socket的,因此是... 查看详情

基于websocket实现网页版聊天室(代码片段)

  WebSocket,HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议,其使用简单,应用场景也广泛,不同开发语言都用种类繁多的实现,仅Java体系中,Tomcat,Jetty,Spring等都提供了对WS的API支持。本篇不做理论探究,仅自娱... 查看详情

使用python实现一个hello/hi的简单的网络聊天程序(代码片段)

一、TCP/IP协议通信原理   TCP/IP协议包含的范围非常的广,它是一种四层协议,包含了各种硬件、软件需求的定义。TCP/IP协议确切的说法应该是TCP/UDP/IP协议。UDP协议(UserDatagramProtocol用户数据报协议),是一种保护消息边界的... 查看详情

用c++编写一个简单的基于tcp协议的网络程序(代码片段)

相关函数socket(intfamily,inttype,intprotocol);bind(intsockfd,conststructsockaddr*server_addr,socklen_taddrlen);listen(intsockfd,intbacklog);accept(intsockfd,structsockaddr*client_addr,socklen_taddrlen);co 查看详情

用c++编写一个简单的基于tcp协议的网络程序(代码片段)

相关函数socket(intfamily,inttype,intprotocol);bind(intsockfd,conststructsockaddr*server_addr,socklen_taddrlen);listen(intsockfd,intbacklog);accept(intsockfd,structsockaddr*client_addr,socklen_taddrlen);co 查看详情

java网络编程基础---基于tcp的简单聊天系统

实现思路:    要实现消息的发送,客户端每次在连接服务器端时都需要告诉服务器自己的用户名,以便能够接收到发送给自己的消息。服务器端在接收到消息时,能够查到对应用户名的客户端,将消息发送给该客... 查看详情

vc++6.0编的基于mfc的简单的tcp聊天程序

有客户端和服务器,能发送接收消息,有简单的界面参考技术A4.1服务器端代码开启服务器功能:voidOnServerOpen()//开启服务器功能WSADATAwsaData;intiErrorCode;charchInfo[64];if(WSAStartup(WINSOCK_VERSION,&wsaData))//调用WindowsSocketsDLLMessageBeep(MB_ICONSTOP);Me... 查看详情

网络编程案例多任务版tcp服务端程序开发(代码片段)

案例-多任务版TCP服务端程序开发案例-多任务版TCP服务端程序开发1.需求2.具体实现步骤3.多任务版TCP服务端程序的示例代码4.小结模拟QQ聊天-客户端模拟QQ聊天-服务端案例-多任务版TCP服务端程序开发学习目标能够说出多任务版TCP... 查看详情

基于tcp的网络聊天系统(代码片段)

目录一、前言二、产品的介绍1.产品具有的功能2.产品的各个模块 3.使用的开发工具以及应用的技术三、产品的设计1.服务端1.1服务端总流程图1.2数据库及其管理模块设计1.3用户管理模块设计1.4业务模块设计1.5消息的操作1.6消息... 查看详情

一个简单的hello/hi的网络聊天程序(代码片段)

TCP套接字函数了解socket函数为了执行网络I/O,一个进程必须做的第一件事情就是调用socket函数,指定期望的通信协议类型(使用ipv4的TCP、使用ipv6的UDP、Unix域字节流协议等)#include<sys/socket.h>intsocket(intfamily,inttype,intprotocol);返... 查看详情

java网络编程案例---聊天室

  网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来。  java.net包中JavaSE的API包含有类和接口,它们提供低层次的通信细节。你可以直接使用这些类和接口,来专注于解决问题,而不用关注... 查看详情

java实现一个简单的网络聊天程序(代码片段)

代码服务器端packagesocket_demo;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.ServerSocket;importjava.net.Socket;publicclassserverpublicstaticvoidmain(String[]args)throwsException//监听 查看详情

基于python完成一个hello/hi的简单的网络聊天程序(代码片段)

一、Socket套接字简介套接字(socket)是一个抽象层,应用程序可以通过它发送或接收数据,可对其进行像对文件一样的打开、读写和关闭等操作。套接字允许应用程序将I/O插入到网络中,并与网络中的其他应用程序进行通信。网... 查看详情

socket之简单的unity3d聊天室__tcp协议(代码片段)

服务器端程序1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Net;5usingSystem.Net.Sockets;6usingSystem.Text;7usingSystem.Threading.Tasks;8namespace聊天室_服务器端_TCP910classProgram11 查看详情

实现一个的简单的网络聊天程序(代码片段)

  本次实验采用Java语言,编写了一个简单的聊天室程序,可以实现多人之间的聊天。以下将对该程序进行详尽分析,并对比分析该编程语言提供的网络接口API与LinuxSocketAPI之间的关系。1、网络通信相关要素1)协议  通信的... 查看详情

java利用tcp编程实现简单聊天室

...编程。  TCP传输控制协议是一种面向连接的、可靠的、基于字节流的传输层通信协议,在Java中我们利用ServerSocket类来建立服务端,利用Socket类来建立客户端。这里要注意,在TCP中,Socket实际上是指Ser 查看详情