亲宝软件园·资讯

展开

java聊天功能

数据结构做不对 人气:0

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

思路:

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();
            }
        }
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论