21xrx.com
2024-12-23 05:03:19 Monday
登录
文章检索 我的文章 写文章
Java简单聊天程序代码实现
2023-06-16 11:19:02 深夜i     --     --
Java Socket实现

随着互联网的发展,聊天已经成为了人们生活中必不可少的一个部分。为了方便用户之间的沟通,开发一款简单的聊天程序是非常有必要的。现在,我们就来介绍一下基于Java的简单聊天程序代码实现。

实现思路:

使用Java Socket实现,客户端连接服务器端,服务器端接受客户端连接,然后将客户端消息发送给服务器端,并将服务器端消息返回给客户端。需要先启动服务器端,然后才能启动客户端。

代码实现:

服务器端代码:


import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class Server {

  public static void main(String[] args) {

    try {

      ServerSocket server = new ServerSocket(8899);

      System.out.println("服务器已经启动...");

      while (true) {

        Socket socket = server.accept();

        ServerThread thread = new ServerThread(socket);

        thread.start();

      }

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

class ServerThread extends Thread {

  private Socket socket;

  public ServerThread(Socket socket)

    this.socket = socket;

  

  @Override

  public void run() {

    try {

      InputStream in = socket.getInputStream();

      byte[] buffer = new byte[1024];

      int count = -1;

      StringBuffer sb = new StringBuffer();

      while ((count = in.read(buffer)) != -1) {

        String str = new String(buffer, 0, count, "UTF-8");

        sb.append(str);

      }

      System.out.println("收到客户端消息:" + sb.toString());

      OutputStream out = socket.getOutputStream();

      out.write("收到了你的消息".getBytes("UTF-8"));

      out.flush();

      out.close();

      in.close();

      socket.close();

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

客户端代码:


import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

public class Client {

  public static void main(String[] args) {

    try {

      Socket socket = new Socket("127.0.0.1", 8899);

      OutputStream out = socket.getOutputStream();

      out.write("你好,我是客户端".getBytes("UTF-8"));

      InputStream in = socket.getInputStream();

      byte[] buffer = new byte[1024];

      int count = -1;

      StringBuffer sb = new StringBuffer();

      while ((count = in.read(buffer)) != -1) {

        String str = new String(buffer, 0, count, "UTF-8");

        sb.append(str);

      }

      System.out.println("收到服务器端消息:" + sb.toString());

      out.flush();

      out.close();

      in.close();

      socket.close();

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

关键词:

Java Socket实现、服务器端、客户端

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章