socket点对点通信实现聊天室功能

一个基于socket连接的实现一个简单的聊天室。废话不多说,直接上代码:

客户端实现代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TcpClient {
    private Socket socket;
    private BufferedReader bufferedReader;
    private PrintWriter printWriter;

    public TcpClient(String ip,String port) {
        try {
            this.socket = new Socket(ip,Integer.parseInt(port));//创建socket连接
            System.out.println("client:" + socket);
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter = new PrintWriter(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMsg(String msg) {//发送消息
        printWriter.println(msg);
        printWriter.flush();
    }

    public String reciveMsg() {//接收消息
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

服务器端实现代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    private ServerSocket serverSocket;
    private Socket socket;
    private BufferedReader bufferedReader;
    private PrintWriter printWriter;

    public TcpServer(String port) {
        try {
            this.serverSocket = new ServerSocket(Integer.parseInt(port));//创建服务器端套接字
            System.out.println("server" + serverSocket);
            socket = serverSocket.accept();//等待客户端连接
            System.out.println("server:" + socket);
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter = new PrintWriter(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMsg(String msg) {//发送消息
        printWriter.println(msg);
        printWriter.flush();
    }

    public String reciveMsg() {//接收消息
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean isClose() {//关闭socket
        return socket.isClosed();
    }
}

客户端界面及创建客户端对象:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;

public class TCP_Server {

    private JFrame frmChatapp;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JTextField textField_4;

    private JTextArea textArea;

    private TcpServer tcpServer;
    private TcpClient tcpClient;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TCP_Server window = new TCP_Server();
                    window.frmChatapp.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TCP_Server() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmChatapp = new JFrame();//界面
        frmChatapp.setTitle("ChatRoom");
        frmChatapp.setBounds(100, 100, 936, 652);
        frmChatapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmChatapp.getContentPane().setLayout(null);

        JLabel lblNewLabel = new JLabel("对方IP");//对方IP
        lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 18));
        lblNewLabel.setBounds(40, 30, 122, 20);
        frmChatapp.getContentPane().add(lblNewLabel);

        textField = new JTextField();//对方IP
        textField.setFont(new Font("宋体", Font.PLAIN, 18));
        textField.setBounds(110, 29, 183, 23);
        frmChatapp.getContentPane().add(textField);
        textField.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("用户名");//用户名
        lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 18));
        lblNewLabel_1.setBounds(40, 82, 58, 20);
        frmChatapp.getContentPane().add(lblNewLabel_1);

        textField_1 = new JTextField();//用户名
        textField_1.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_1.setBounds(110, 80, 183, 23);
        frmChatapp.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        JLabel label = new JLabel("端口号");//端口号
        label.setFont(new Font("宋体", Font.PLAIN, 18));
        label.setBounds(619, 34, 66, 20);
        frmChatapp.getContentPane().add(label);

        textField_2 = new JTextField();//端口号
        textField_2.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_2.setBounds(695, 31, 183, 23);
        frmChatapp.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        JLabel label_1 = new JLabel("本机端口号");//本机端口号
        label_1.setFont(new Font("宋体", Font.PLAIN, 18));
        label_1.setBounds(585, 86, 92, 20);
        frmChatapp.getContentPane().add(label_1);

        textField_3 = new JTextField();//本机端口号
        textField_3.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_3.setBounds(695, 83, 183, 23);
        frmChatapp.getContentPane().add(textField_3);
        textField_3.setColumns(10);

        JButton button = new JButton("绑定端口号");//绑定端口号
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String ip = textField.getText();
                String port = textField_2.getText();
                tcpClient = new TcpClient(ip,port);//新建客户端
                String localport = textField_3.getText();
                tcpServer = new TcpServer(localport);
                ReciveMsg reciveMsg = new ReciveMsg();
                reciveMsg.start();
            }
        });
        button.setFont(new Font("宋体", Font.PLAIN, 18));
        button.setBounds(366, 82, 155, 23);
        frmChatapp.getContentPane().add(button);

        textArea = new JTextArea();
        textArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
        textArea.setBounds(40, 131, 836, 380);
        frmChatapp.getContentPane().add(textArea);

        textField_4 = new JTextField();
        textField_4.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_4.setBounds(40, 545, 692, 23);
        frmChatapp.getContentPane().add(textField_4);
        textField_4.setColumns(10);

        JButton button_1 = new JButton("发送");//发送
        button_1.setFont(new Font("宋体", Font.PLAIN, 18));
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = textField_1.getText();
                System.out.println(username + ":" + textField_4.getText());
                tcpClient.sendMsg(username + ":" + textField_4.getText());
                System.out.println("发送数据成功!!!");
            }
        });
        button_1.setBounds(779, 546, 97, 23);
        frmChatapp.getContentPane().add(button_1);
    }

    private class ReciveMsg extends Thread {
        @Override
        public void run() {
            while (true) {
                String str = tcpServer.reciveMsg();//接收消息
                if (str == null) {
                    break;
                }
                textArea.append(str + "\n");//把接收到的消息加入到文本域
                System.out.println("接收数据成功!!!");
            }
        }
    }

}

服务器端界面及创建代码:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;

public class TCP_Server2 {

    private JFrame frmChatapp;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JTextField textField_4;

    private JTextArea textArea;

    private TcpServer tcpServer;
    private TcpClient tcpClient;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TCP_Server2 window = new TCP_Server2();
                    window.frmChatapp.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TCP_Server2() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmChatapp = new JFrame();
        frmChatapp.setTitle("ChatRoom");
        frmChatapp.setBounds(100, 100, 936, 652);
        frmChatapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmChatapp.getContentPane().setLayout(null);

        JLabel lblNewLabel = new JLabel("对方IP");//对方IP
        lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 18));
        lblNewLabel.setBounds(40, 30, 122, 20);
        frmChatapp.getContentPane().add(lblNewLabel);

        textField = new JTextField();//对方IP
        textField.setFont(new Font("宋体", Font.PLAIN, 18));
        textField.setBounds(110, 29, 183, 23);
        frmChatapp.getContentPane().add(textField);
        textField.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("用户名");//用户名
        lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 18));
        lblNewLabel_1.setBounds(40, 82, 58, 20);
        frmChatapp.getContentPane().add(lblNewLabel_1);

        textField_1 = new JTextField();//用户名
        textField_1.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_1.setBounds(110, 80, 183, 23);
        frmChatapp.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        JLabel label = new JLabel("端口号");//端口号
        label.setFont(new Font("宋体", Font.PLAIN, 18));
        label.setBounds(619, 34, 66, 20);
        frmChatapp.getContentPane().add(label);

        textField_2 = new JTextField();//端口号
        textField_2.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_2.setBounds(695, 31, 183, 23);
        frmChatapp.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        JLabel label_1 = new JLabel("本机端口号");//本机端口号
        label_1.setFont(new Font("宋体", Font.PLAIN, 18));
        label_1.setBounds(585, 86, 92, 20);
        frmChatapp.getContentPane().add(label_1);

        textField_3 = new JTextField();//本机端口号
        textField_3.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_3.setBounds(695, 83, 183, 23);
        frmChatapp.getContentPane().add(textField_3);
        textField_3.setColumns(10);

        JButton button = new JButton("绑定端口号");//绑定端口号
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String ip = textField.getText();
                String localport = textField_3.getText();
                tcpServer = new TcpServer(localport);

                String port = textField_2.getText();
                tcpClient = new TcpClient(ip,port);
                ReciveMsg reciveMsg = new ReciveMsg();
                reciveMsg.start();

            }
        });
        button.setFont(new Font("宋体", Font.PLAIN, 18));
        button.setBounds(366, 82, 155, 23);
        frmChatapp.getContentPane().add(button);

        textArea = new JTextArea();
        textArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
        textArea.setBounds(40, 131, 836, 380);
        frmChatapp.getContentPane().add(textArea);

        textField_4 = new JTextField();
        textField_4.setFont(new Font("宋体", Font.PLAIN, 18));
        textField_4.setBounds(40, 545, 692, 23);
        frmChatapp.getContentPane().add(textField_4);
        textField_4.setColumns(10);

        JButton button_1 = new JButton("发送");//发送
        button_1.setFont(new Font("宋体", Font.PLAIN, 18));
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = textField_1.getText();
                System.out.println(username + ":" + textField_4.getText());
                tcpClient.sendMsg(username + ":" + textField_4.getText());
                System.out.println("发送数据成功!!!");
            }
        });
        button_1.setBounds(779, 546, 97, 23);
        frmChatapp.getContentPane().add(button_1);
    }

    private class ReciveMsg extends Thread {
        @Override
        public void run() {
            while (true) {
                String str = tcpServer.reciveMsg();
                if (str == null) {
                    break;
                }
                textArea.append(str + "\n");
                System.out.println("接收数据成功!!!");
            }
        }
    }

}

运行截图:
在这里插入图片描述左边为服务器端,右边为客户端,运行时,输入完毕信息后,先点击左边的绑定端口号,再点击右边的绑定端口号。
(博主为一名学生,比较懒惰,如果有有什么需要的学校作业,可以在下方留言,如果有我会发出来的)。

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 很高兴回答你的问题。用C语言写一个点对点即时通信程序,首先需要构建套接字socket的链接,实现两台电脑间一对一的通信;其次,要实现多线程功能,可以实现多个电脑间的通信;此外,还需要在通信过程中对发送的信息进行加密及解密处理;最后,需要完成多人实时聊天室功能。 ### 回答2: 使用C语言编写一个点对点即时通信系统可以按照以下步骤实现: 1. 构建套接字socket的链接:使用socket函数创建一个套接字,并使用bind函数将套接字绑定到本地IP和端口上,然后使用listen函数监听这个套接字。 2. 实现多线程功能:使用pthread库创建多个线程,每个线程代表一个电脑的通信。这些线程可以并行运行,互不影响。 3. 在通信过程中进行加密与解密处理:可以选择合适的加密算法,例如AES、RSA等,使用加密函数对发送的信息进行加密,然后在收到的信息上使用解密函数进行解密处理。确保只有正确的接收方能够解密并读取信息。 4. 完成多人实时聊天室:当多个电脑都能够建立起通信后,用户可以发送和接收信息。可以使用send和recv函数来发送和接收信息,并在接收信息时使用线程进行处理并显示在聊天室界面上。 总结:以上是使用C语言编写一个点对点即时通信系统的大致步骤,可以根据实际需求和具体细节进行适当调整和实现。 ### 回答3: 使用C语言编写一个点对点即时通信系统,需要考虑以下几个方面的实现: 1. 构建套接字socket的链接,实现两台电脑间一对一的通信: 使用C语言中的socket库函数,分别在两台电脑上创建套接字,使用TCP协议建立连接。其中一个电脑作为客户端,另一个作为服务器端。客户端通过指定服务器的IP地址和端口号连接到服务器端。 2. 实现多线程功能,可以实现多个电脑间的通信: 在服务器端使用多线程来处理来自不同客户端的消息。每当一个客户端连接到服务器端时,服务器端通过创建一个新的线程来与该客户端进行通信。这样可以同时处理多个客户端的消息实现多个电脑间的通信。 3. 在通信过程中对发送的信息进行加密及解密处理: 可以使用C语言中的加密函数库或自定义加密算法来对发送的信息进行加密。在服务器端和客户端中实现相同的加密和解密算法,保证消息的安全性。加密后的信息在网络传输中,即使被截获也无法直接获取其内容。 4. 完成多人实时聊天室: 在服务器端维护一个消息队列,每当一个客户端发送消息时,将消息加入到队列中。服务器端不断检查消息队列,将消息发送给所有连接到服务器的客户端。客户端通过不断接收服务器端发送的消息实现实时聊天。可以通过给消息增加时间戳和发送者的信息等来实现更完善的聊天室功能。 以上是一个基本的实现思路,当然具体的实现还需要考虑更多细节和交互逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值