java聊天功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java聊天功能

数据结构做不对   2022-09-29 我要评论

应用客户端和服务端通过控制台的输入输出实现简易聊天功能

思路:

1.创建服务端类ChatServerThread和客户端类ChatClientThradd

2.创建发送类Sendlmpl和接收类Receivelmpl

3.在服务端类中监听8888号端口,并开启发送和接收线程

4.在客户端类中连接8888号端口并开启发送和接收线程

5.在发送类中,开启线程循环,发送用户输入的信息

6.在接收类中,开启线程循环,接收网络发送的数据

代码实现

服务端ChatServerThread

package test;

import java.net.ServerSocket;
import java.net.Socket;

public class  ChatServerThread{
    //服务端
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(8888);
        //监听8888号端口
        Socket socket = serverSocket.accept();
        //开启发送和接收线程
        Sendlmpl sendlmpl=new Sendlmpl(socket);
        new Thread(sendlmpl).start();
        Receivelmpl receivelmpl=new Receivelmpl(socket);
        new Thread(receivelmpl).start();
    }
}

客户端ChatClientThradd

package test;

import test.Receivelmpl;
import test.Sendlmpl;

import java.net.Socket;

public class ChatClientThradd {
    //客户端
    public static void main(String[] args) throws Exception{
        //连接8888号端口
        Socket socket=new Socket("127.0.0.1",8888);
        //开启发送和接收线程
        Sendlmpl sendlmpl=new Sendlmpl(socket);
        new Thread(sendlmpl).start();
        Receivelmpl receivelmpl=new Receivelmpl(socket);
        new Thread(receivelmpl).start();
    }
}

发送类Sendlmpl :

package test;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Sendlmpl implements Runnable {
    //发送类
    private Socket socket;

    public Sendlmpl(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        //线程循环,发送用户输入的信息
        while (true) {
            try {
                OutputStream outputStream =socket.getOutputStream();
                String string=scanner.nextLine();
                outputStream.write(string.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

接收类Receivelmpl :

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Receivelmpl implements Runnable{
    //接收类
    private Socket socket;

    public Receivelmpl(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //循环接收网络发来的信息
        while (true) {
            try {
                InputStream inputStream=socket.getInputStream();
                byte [] bytes=new byte[1024];
                int z=inputStream.read(bytes);
                System.out.println(new String(bytes,0,z));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们