⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.java

📁 JAVA网络聊天室.运用网络编程、文件操作、数据流处理以及多线程等基础技术编写一个网络聊天室.
💻 JAVA
字号:
/*****************************************************************************************/
////////////////////////////////////////服务端源文件////////////////////////////////////////
/*****************************************************************************************/
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;

class Server
{
    boolean started = false;
    ServerSocket ss = null;
    ServerSocket cns = null;
    Socket s;
    ClientRun cr;
    List<ClientRun> list = new ArrayList<ClientRun>();

    public static void main(String[] args) 
    {
        new Server().start();
    }

    public void start()
    {
        System.out.println("夜雪聊天室服务器启动...");
        JOptionPane.showMessageDialog(null, "夜雪聊天室服务器正在启动中...\n若你需深入了解服务器工作进度\n建议使用MS-DOS命令行模式启动服务端", "服务器启动", JOptionPane.CLOSED_OPTION);
        try
        {
            ss = new ServerSocket(8888);   //创建两个ServerSocket对象。[8888]端口用于聊天界面通信,
            cns = new ServerSocket(1001);  //[1001]端口用于客户注册已经登陆验证的通信
            started = true;
        }
        catch (BindException BE)
        {
            System.out.println("端口使用中!");
            JOptionPane.showMessageDialog(null, "[8888]端口正在使用中!!!", "端口出错!", JOptionPane.ERROR_MESSAGE);
        }
	catch (IOException E)
	{
            System.out.println("服务器连接失败!");
        }
	try
	{
            while (started)
            {
                new LrRun(cns);

                s = ss.accept();
                cr = new ClientRun(s);   //主线程只负责接收信息,每个客户端连接进来都会开始一个新线程
                new Thread(cr).start();  //把连接进来的Socket传到线程中。
                list.add(cr);
            }
        }
	catch (IOException E)
	{
            System.out.println("Client Closed!");
	}
    }

    class LrRun implements Runnable
    {
        ServerSocket svrs;
        Socket cmt;
	Thread serverThread;
        boolean bConnect = false;
        public LrRun(ServerSocket s)
        {
            svrs = s;
            try
            {
                serverThread = new Thread(this);
		serverThread.start();
		bConnect = true;
            }
            catch (Exception E)
            {
                System.out.println("不能监听客户请求: " + E);
            }
        }
        public void run()
        {
            try
            {
                while (bConnect)
                {
                    cmt = svrs.accept();
                    System.out.println("系统提示:" + cmt.getInetAddress() + "试图连接登陆");
                    Connect con = new Connect(cmt);
                }
            }
            catch (Exception E)
            {
                System.out.println("系统提示:验证终端断开链接!");
            }
            finally
            {
                try
                {
                    if (cmt != null)
                    {
                        cmt.close();
                        cmt = null;
                    }
                }
                catch (IOException io)
                {
                    io.printStackTrace();
                 }
            }
        }
    }

    /*****************************多线程实现多客户端同时连接************************************/
    class ClientRun implements Runnable
    {
        private Socket s;
        private DataInputStream dis = null;
        private DataOutputStream dos = null;
        boolean bConnect = false;
        
        public ClientRun(Socket s)                        
	{
            this.s = s;
            try
            {
                System.out.println("系统提示:" + s.getInetAddress() + "已经联入");
                dis = new DataInputStream(s.getInputStream());   
		dos = new DataOutputStream(s.getOutputStream());
		bConnect = true;
            }
            catch (IOException E)
            {
                E.printStackTrace();
            }
        }

	public void send(String str)
	{
            try
            {
                dos.writeUTF(str);
            }
            catch (IOException E)
            {
                E.printStackTrace();
            }
        }
        
	public void run()
	{
            try
            {
                while (bConnect)
                {
                        String str = dis.readUTF();
                        System.out.println(str);
                        for (int i = 0; i < list.size(); i++ )
                        {
                            ClientRun cr = list.get(i);
			    cr.send(str);
                        }
                }
            }
            catch (Exception E)
            {
                System.out.println("系统提示:" + s.getInetAddress() + "离开了!");
            }
            finally
            {
                try
                {
                    if (dis != null) dis.close();
                    if (dos != null) dos.close();
                    if (s != null)
                    {
                        s.close();
                        s = null;
                    }
                }
                catch (IOException io)
                {
                    io.printStackTrace();
                }
            }
        }
    }
}
/**************************************Connect类******************************************/
class Connect
{
    ObjectOutputStream streamToClient;
    int ctr = 0;
    
    BufferedReader streamFromClient;
    static Vector vector;
    static Vector vctrList;
    String message = " ";
    static String str = new String("用户列表");
    
    static
    {
        vector = new Vector(1, 1);
	vctrList = new Vector(1, 1);
	vctrList.addElement((String)str);
    }
    /*********************************登陆信息有效性的检查*************************************/
    int verify(String mesg)
    {
        try
	{
            RandomAccessFile RAS = new RandomAccessFile("UsrPwd.txt", "r");
            int i = 0;
            String str = "";
            while ((RAS.getFilePointer()) != (RAS.length()))
            {
                str = RAS.readLine();
		if (str.equals(mesg))
		{
                    ctr = 1;
                    break;
                }
            }
            RAS.close();
        }
	catch (Exception E){}
        return ctr;
    }
    /************************************注册信息检查*******************************************/
    int checkFile(String mesg)
    {
        int chk = 1;
	try
	{
            RandomAccessFile RS = new RandomAccessFile("UsrPwd.txt", "r");
            int i = 0;

            String str = "";
            String colon = new String(":");
            int index = ((String)mesg).lastIndexOf(colon);

            String userName = (String)mesg.substring(0, index);
            while ((RS.getFilePointer()) != (int)(RS.length()))
            {
                str = RS.readLine();
		int index1 = ((String)str).lastIndexOf(colon);
		String usrName = (String)str.substring(0, index1);
		if (usrName.equals(userName))
		{
                    chk = 0;
                    break;
                }
            }
            RS.close();
        }
        catch (Exception E){}
        return chk;
    }
    /**************************************构造函数********************************************/
    public Connect(Socket inFromClient)
    {
        String msg = "";  //提取客户端的流
	String mesg = "";
	try
	{
            streamFromClient = new BufferedReader(new InputStreamReader(inFromClient.getInputStream()));
            streamToClient = new ObjectOutputStream(inFromClient.getOutputStream());
            msg = streamFromClient.readLine();
            if (msg.equals("LoginInfo"))
            {
                msg = streamFromClient.readLine();
		int ver = verify(msg);
		if (ver == 1)
		{
                    String colon = new String(":");
                    int index = ((String)msg).lastIndexOf(colon);
                    String userName = (String)msg.substring(0, index);
                    if (!(vctrList.indexOf((String)userName) > 0))
                    {
			streamToClient.writeObject("Welcome");
			vctrList.addElement((String)userName);
                    }
                }
                else
		{
                    streamToClient.writeObject("Login Deny");
		}
            }
            
            else if (msg.equals("RegisterInfo"))
            {
                msg = streamFromClient.readLine();
		int ret = checkFile(msg);
		if (ret == 0)
		    streamToClient.writeObject("User Exists");
		if (ret == 1)
		{
                    FileOutputStream out = new FileOutputStream("UsrPwd.txt", true);
                    PrintStream p = new PrintStream(out);
                    p.println();
                    p.println(msg);
                    p.close();
                    streamToClient.writeObject("Registered");
		}
            }
            else
            {
                message = message + msg;
		vector.addElement((String)message);
		streamToClient.writeObject(vector);
            }
        }
	catch (Exception E)
	{
            System.out.println("无法获取客户端的流对象 " + E);
	}
	finally
	{
            try
            {
		inFromClient.close();
            }
            catch (IOException E){}
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -