欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java使用TCP套接字实现多人聊天功能详解

时间:2021-01-11 11:00:19|栏目:JAVA代码|点击:

本文实例讲述了Java使用TCP套接字实现多人聊天功能。分享给大家供大家参考,具体如下:

废话不多说,直接开搞:

先创建一个服务端:

package interWebWriterEven2;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/**
 * 服务端
 * @author
 *
 */
public class ServiceT {
    static ArrayList<Socket> list = new ArrayList<Socket>();
    public static void main(String[] args) {
        ServerSocket server;
        try {
            server = new ServerSocket(9999);
            while(true){
                Socket socket = server.accept();
                System.out.println(socket.getInetAddress().getHostName()+"连接成功。IP:"+socket.getInetAddress().getHostAddress());
                list.add(socket);
                ServiceThreadT t =new ServiceThreadT(socket);
                t.start();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

接着是服务端的线程:

package interWebWriterEven2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
/**
 * 服务端线程
 * @author
 *
 */
public class ServiceThreadT extends Thread{
    private Socket socket;
    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        this.socket = socket;
    }
    public ServiceThreadT(Socket socket) {
        super();
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            @SuppressWarnings("resource")
            BufferedWriter wFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D://messagesT.txt",true)));
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String strOut = "";
            String strIn = "";
            while(true){
                strIn = socket.getInetAddress().getHostName()+":"+br.readLine();
                strOut = strIn;
                wFile.write(strIn);
                wFile.newLine();
                wFile.flush();
                for (Socket soc : ServiceT.list) {
                    if(soc != socket){
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
                        bw.write(strOut);
                        System.out.println(strOut);
                        bw.newLine();
                        bw.flush();
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

然后是客户端(应用端):

package interWebWriterEven2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
/**
 * 客户端
 * @author
 *
 */
public class ClientT {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",9999);
            ClientThreadT t = new ClientThreadT(socket);
            t.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String strIn = "";
            while(true){
                strIn = br.readLine();
                System.out.println(strIn);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

最后是客户端的线程:

package interWebWriterEven2;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
/**
 * 客户端的线程
 * @author
 *
 */
public class ClientThreadT extends Thread{
    private Socket socket;
    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        this.socket = socket;
    }
    public ClientThreadT(Socket socket) {
        super();
        this.socket = socket;
    }
    @Override
    public void run() {
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            while(true){
                System.out.println();
                bw.write(sc.nextLine().trim());
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

先运行服务端哦,否则将会报空指针异常的。

更多关于java相关内容感兴趣的读者可查看本站专题:《Java Socket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

上一篇:java使用Socket实现SMTP协议发送邮件

栏    目:JAVA代码

下一篇:springboot 监控管理模块搭建的方法

本文标题:Java使用TCP套接字实现多人聊天功能详解

本文地址:http://www.codeinn.net/misctech/43494.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有