21xrx.com
2024-11-22 11:55:22 Friday
登录
文章检索 我的文章 写文章
Java实现聊天功能:基于Socket的网络通信
2023-06-14 21:10:05 深夜i     --     --
Java Socket 聊天功能

Java作为一门跨平台的编程语言,很适合用来实现网络通信功能。本文将介绍基于Java Socket实现聊天功能的代码案例。

先看一下通信流程:

![聊天功能流程图](https://i.imgur.com/qZgOk5O.png)

代码实现如下:


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

public class ChatServer {

  private static ArrayList socketList = new ArrayList ();

  public static void main(String[] args) throws Exception {

    ServerSocket server = new ServerSocket(5000);

    System.out.println("The chat server is running.");

    while (true) {

      Socket socket = server.accept();

      socketList.add(socket);

      new Thread(new ServerThread(socket)).start();

    }

  }

  static class ServerThread implements Runnable {

    private Socket socket;

    private BufferedReader in;

    private PrintWriter out;

    public ServerThread(Socket socket) throws Exception {

      this.socket = socket;

      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

      out = new PrintWriter(socket.getOutputStream(), true);

    }

    public void run() {

      try {

        while (true) {

          String str = in.readLine();

          System.out.println("Server received: " + str);

          if (str.equals("exit"))

            break;

          

          for (Socket s : socketList) {

            PrintWriter writer = new PrintWriter(s.getOutputStream(), true);

            writer.println(str);

          }

        }

      } catch (Exception e) {

        System.out.println("Error: " + e.getMessage());

      } finally {

        try {

          in.close();

          out.close();

          socketList.remove(socket);

          socket.close();

        } catch (Exception e) {

          System.out.println("Error: " + e.getMessage());

        }

      }

    }

  }

}

上面的代码是基于ServerSocket实现的服务器端,下面是基于Socket实现的客户端:


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

import java.util.Scanner;

public class ChatClient {

  private BufferedReader in;

  private PrintWriter out;

  public static void main(String[] args) throws Exception {

    ChatClient client = new ChatClient();

    client.initialize();

  }

  public void initialize() throws Exception {

    Socket socket = new Socket("localhost", 5000);

    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    out = new PrintWriter(socket.getOutputStream(), true);

    Scanner scanner = new Scanner(System.in);

    String str;

    while (true) {

      System.out.print(">>> ");

      str = scanner.nextLine();

      out.println(str);

      if (str.equals("exit"))

        break;

      

      System.out.println(in.readLine());

    }

    in.close();

    out.close();

    socket.close();

  }

}

上面的代码是基于Socket实现的客户端,它接收用户从控制台输入的信息,将信息发送给服务器端。同时也会接收服务器端传回来的消息并将其打印到控制台上。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复