使用JAVA编程实现多人聊天室(需要用到多线程)没有可视化,但可以应付作业

在网上看到个版本不错,改动了一些后发现可以用。最近要考试了,没时间详细写,暑假有空的话再改写一点东西。给链接看吧。有点遗憾,原来我看到博客想出现(你)+信息,但我在使用时发现有问题,就没使用了。

一、实验目的

1.熟悉网络编程的基本概念;
2.掌握Socket编程的基本方法和步骤;
3. 学会运用多线程;
4.掌握常见输入/输出流类的使用。

二、实验任务

使用JAVA编程实现多人聊天室(需要用到多线程)
三、实验内容
1.使用JAVA编程实现多人聊天室(需要用到多线程),并要求服务器端至少包含如下功能:
(1)若有新用户连接,则向已经连接到服务端的用户发送用户上线消息。
(2)若有用户断开连接,则向在线用户发送用户下线消息。
(3)若有用户发送消息,则向所有用户转发该消息。
(4)当停止服务时,断开所有用户连接。

三、实验结果记录(程序运行结果截图)

1.运行结果:在这里插入图片描述
停止服务时,
在这里插入图片描述

四.代码区:

一.用户1的代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
import java.io.*;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

class client implements Runnable {// 客户端
    static Socket socket = null;
    Scanner input = new Scanner(System.in);
    static String name=null;
    public static void main(String[] args) {
        int x=(int)(Math.random()*100);
        client.name="client"+x;
        System.out.println("************客户端"+x+"*************");
        try {
            socket = new Socket("127.0.0.1", 9999);
            // System.out.println("已经连上服务器了");
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            out.println("客户端"+x+"已经连上服务器了");
            out.flush();

        } catch (Exception e) {
            System.out.println("服务器已经断网");
        }
        client t = new client();
        Read r = new Read(socket);
        Thread print = new Thread(t);
        Thread read = new Thread(r);
        print.start();
        read.start();
    }
    public void run() {

        try {
            Thread.sleep(1000);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            while (true) {
                String msg = input.nextLine();
                String Name=name;
                if(msg.equals("bye"))
                {  out.println(Name+"说"+msg+"后下线了");
                    out.flush();   socket.close();  break;
                }
                else{
                    out.println(Name+"说:"+msg);
                    out.flush();
                }
            }
        } catch (Exception e) {
            System.out.println("断网了");
        }
    }
}

二、用户2的代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
import java.io.*;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
class client1 implements Runnable {// 客户端
    static Socket socket = null;
    Scanner input = new Scanner(System.in);
    static String name=null;
    public static void main(String[] args) {
        int x=(int)(Math.random()*100);
        client1.name="client"+x;
        System.out.println("************客户端"+x+"*************");
        try {
            socket = new Socket("127.0.0.1", 9999);
            // System.out.println("已经连上服务器了");
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            out.println("客户端"+x+"已经连上服务器了");
            out.flush();

        } catch (Exception e) {
            System.out.println("服务器已经断网");
        }
        client1 t = new client1();
        Read r = new Read(socket);
        Thread print = new Thread(t);
        Thread read = new Thread(r);
        print.start();
        read.start();
    }
    public void run() {

        try {
            Thread.sleep(1000);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            while (true) {
                String msg = input.nextLine();
                String Name=name;
                if(msg.equals("bye"))
                {  out.println(Name+"说"+msg+"后下线了");
                    out.flush();    socket.close(); break;
                }
                else{
                    out.println(Name+"说:"+msg);
                    out.flush();
                }
            }
        } catch (Exception e) {
            System.out.println("服务器链接故障");
        }
    }
}

二、用户接受信息区:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.net.Socket;
import java.util.Scanner;
public class Read implements Runnable {
    static Socket socket = null;

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

    public void run() {
        try {
            Thread.sleep(1000);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
            while (true) {
                System.out.println(in.readLine());
            }
        } catch (Exception e) {
            System.out.println("服务器连接故障");
        }
    }
}

三.服务器区:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class server implements Runnable {// 服务端
    static List<Socket> socketList=new ArrayList<Socket>();
    // 读取 In
    static Socket socket = null;
    static ServerSocket serverSocket = null;
    public server() {// 构造方法
        try {
            serverSocket = new ServerSocket(9999);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("************服务端*************");
        server t = new server();
        int count = 0;
        while (true) {
            try {
     //              System.out.println("端口9999等待被连接......");
                socket = serverSocket.accept();
                count++;
                System.out.println("第" + count + "个客户已连接");
                socketList.add(socket);
            } catch (IOException e) {
              System.out.println("第"+count+"个客户没连接上");
            }
            Print p = new Print(socket);
            Thread read = new Thread(t);
            Thread print = new Thread(p);
            read.start();
            print.start();
        }
    }
    public void run() {
        // 重写run方法
        try {
            Thread.sleep(1000);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                String jieshou = in.readLine();
                System.out.println( jieshou);
                for (int i = 0; i < socketList.size(); i++) {
                    Socket socket=socketList.get(i);
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    if (this.socket!=socket) {
                        out.println(jieshou);
                    }else{
                       out.println(jieshou);
                      // out.println("(你)"+jieshou);
                    }
                    out.flush();
                }
            }
        }
         catch (Exception e) {

            String jieshou = "已下线了";
            PrintWriter out = null;
            try {
                out = new PrintWriter(socket.getOutputStream());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (socket!=this.socket) {
                out.println(jieshou);
            }else{
                out.println("(你的好友)"+jieshou);
            }
            out.flush();

        }
    }
}

四、服务器接受信息区:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Print implements Runnable {
    static List<Socket> socketList=new ArrayList<Socket>();
    Scanner input = new Scanner(System.in);
    public Print(Socket s) {// 构造方法
        try {
            socketList.add(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void run() {
        try {
            Thread.sleep(1000);
            while (true) {
                String msg = input.nextLine();
                for (int i = 0; i < socketList.size(); i++) {
                    Socket socket=socketList.get(i);
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    // System.out.println("对客户端说:");
                    out.println("服务端说:"+msg);
                    out.flush();
                }
            }
        } catch (Exception e) {
           System.out.println("网络异常");
        }
    }
}

五、其他顾客区不同在:
在这里插入图片描述
在这里插入图片描述
其他一样。

五.分析代码:

import java.io.PrintWriter;
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("客户端"+x+"已经连上服务器了");

当前者的自动清空缓冲区的功能被使能时(构造函数中autoFlush置为true),仅当println()方法被调用时才自动清缓冲区,而不是像PrintStream一样遇到一个换行符就清缓冲。

out.flush();// 刷新该流的缓冲。
if(msg.equals("bye"))
{  out.println(Name+"说"+msg+"后下线了");
    out.flush();   socket.close();  break;
}
else{
    out.println(Name+"说:"+msg);
    out.flush();
}
Thread print = new Thread(t);
Thread read = new Thread(r);
print.start();
read.start();
public void run() {
    try {
        Thread.sleep(1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        while (true) {
           System.out.println(in.readLine());//按行输出        }
    } catch (Exception e) {
        System.out.println("服务器连接故障");
    }
import java.util.ArrayList;//新知识  相当于动态数组

static List<Socket> socketList=new ArrayList<Socket>();
static ServerSocket serverSocket = null;//

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while (true) {
    String jieshou = in.readLine();
    System.out.println( jieshou);
    for (int i = 0; i < socketList.size(); i++) {
        Socket socket=socketList.get(i);
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        if (this.socket!=socket) {
            out.println(jieshou);
        }else{
           out.println(jieshou);
          // out.println("(你)"+jieshou);
        }
        out.flush();
    }

AllayList用法:
https://www.cnblogs.com/skywang12345/p/3308556.html
printWriter用法:
https://blog.csdn.net/evilcry2012/article/details/78457090
https://blog.csdn.net/evilcry2012/article/details/78457090

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广大菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值