聊天功能实现思路

思路:

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

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

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

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

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

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

服务端

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

客户端

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

发送类

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

接收类

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

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值