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

📄 chatserver.java

📁 The chat room application that using JAVA to development.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
///////////////////////////////////////////////////
// Java Programming Course, job-1
// Date: 2008/3/31
///////////////////////////////////////////////////
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

public class ChatServer
{
    // Declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream   
    static  Socket clientSocket = null;
    static  ServerSocket serverSocket = null;
    static  int maxClient = 10;

    // This chat server can accept up to 10 clients' connections
    static  clientThread t[] = new clientThread[10];           
    
    public static void main(String args[]) 
    {
	    // The default port
	    int port_number=8000;
	
	    if (args.length < 1)
		    System.out.println("Usage: java ChatServer [PortNumber]\n"+"Now using port number="+port_number);
	    else 
		    port_number=Integer.valueOf(args[0]).intValue();
	
	    // Initialization section:
	    // Try to open a server socket on port port_number 
        try {
	        serverSocket = new ServerSocket(port_number);
	    }
        catch (IOException e) {
	        System.out.println(e);
        }
        
        System.out.println("ChatServer Running...");
        	    
	    // Create a socket object from the ServerSocket to listen and accept 
	    // connections.
	    // Open input and output streams for this socket will be created in 
	    // client's thread since every client is served by the server in
	    // an individual thread
	    while(true)
	    {
	        try 
	        {
	            int i;
	            
		        clientSocket = serverSocket.accept();
		        for(i=0; i<maxClient; i++)
		        {
		            if(t[i]==null) {
			            (t[i] = new clientThread(clientSocket, t, maxClient)).start();
			            System.out.println(t[i]+" --> Created");
			            break;
			        }
		        }
		        
		        //ChatServer is full, return a message to Client, and close that socket.
		        if (i == maxClient) {
		            PrintStream os = null;		            
		            os = new PrintStream(clientSocket.getOutputStream());
		            os.println("ChatServer full!");           
            	    os.close();
            	    clientSocket.close();		            
		       }
	        }
	        catch (IOException e) {
		        System.out.println(e);
		    }
	    }
    }
} 


// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the 
// server about the fact that a new client has joined the chat room, 
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates. 
class clientThread extends Thread
{
    InputStreamReader bReader = null;
    BufferedReader is = null;
    PrintStream os = null;
    Socket clientSocket = null;       
    clientThread t[];
    String name;
    String postMsg;
    String command[] = new String[5];
    int cnt = 0;
    int max;
    boolean kick = false;
    boolean postCnt = false;

    public clientThread(Socket clientSocket, clientThread[] t, int m)
    {
	    this.clientSocket=clientSocket;
        this.t=t;
        this.max=m;
    }
        
    public void run() 
    {
	    String line;
        StringTokenizer st;
        
	    try
	    {
	        bReader = new InputStreamReader(clientSocket.getInputStream());
            is = new BufferedReader(bReader);
	        
	        os = new PrintStream(clientSocket.getOutputStream());
	        
	        while (true)
	        {
	            int i;
	            
	            os.println("Username: ");
	            name = is.readLine();
	        
	            //Check the name whether is used by others.
	            for (i=0; i<max; i++) {
	                if (t[i] != null && t[i] != this && (name.equals(t[i].name) || name.equals(""))) {
	                    os.println("Error: the user '" +name+"' is already online or unavailable. Please change a name");
	                    break;
	                }
	            }
	            if (i == max)
	                break;
	            
	        }
	                
	        os.println("*******************************************************\r\n" +
	                   "**" + "<" + name + ">, " + "welcome to the chat system.\r\n" +
	                   "*******************************************************\r\n"); 
	    
	        for(int i=0; i<max; i++)
		        if (t[i]!=null && t[i]!=this)  
		            t[i].os.println(name + " is connecting to the chat server");
		            
		    //----------------------------------------
		    //The mainloop to handle all commands
		    //----------------------------------------
	        while (!kick) 
	        {
		        line = is.readLine();
		        
		        // record last commands
		        if (line.startsWith("/")) {
		            command[cnt] = line;
		            if (++cnt == 5)
		                cnt = 0;
		        }

                // true to close this thread.    
		        //if (kick)
		          //  break;
		        
		        st = new StringTokenizer(line);

                //------------------
		        //Handle "exit"
		        //------------------
                if (line.startsWith("/exit"))
                {
                    for(int i=0; i<max; i++)
		                if (t[i]!=null && t[i]!=this)  
		                    t[i].os.println(name + " is leaving the chat server.");
	    
	                os.println("*** Bye "+name+" ***"); 
                    break;
                }
                
                //------------------
                //Handle "yell"
                //------------------
                else if (line.startsWith("/yell "))
                {
                    String msg;

                    msg = line.substring(6);
                    
                    for(int i=0; i<max; i++) {
		                if (t[i]!=null && t[i] != this) {
		                    t[i].os.println(name+" yelled: "+msg);
		                }
		            }
                }
                
                //------------------
                //Handle "tell"
                //------------------
                else if (line.startsWith("/tell "))
                {
                    String msg;
                    String someone;
                    int len;
                    int i;
                    
                    //Don't care the first one
                    st.nextToken();
                    
                    someone = st.nextToken();
                    len = someone.length() + 7;
                    
                    if (line.length() > len)
                        msg = line.substring(len);
                    else
                        msg = null;
                    
                    for (i=0; i<max; i++) {
                        if (t[i] != null && someone.equals(t[i].name)) {
                            t[i].os.println(name + " told " + t[i].name + ": " + msg);
                            break;
                        }
                    }
                    if (i == max)
                        os.println("The person "+someone+" is not available.");
                }                
                
                //------------------
                //Handle "post"
                //------------------
                else if (line.startsWith("/post "))
                {
                    boolean flag = false;
                    while (true) {
                        if (postCnt == false) {
                            postMsg = line.substring(6);                   
                            for(int i=0; i<max; i++)
		                        if (t[i]!=null && t[i]!=this)  
		                            t[i].os.println(name + " post a msg.");
		                        
                            postCnt = true;
                            break;
                        }
                        else {
                            if (!flag) {
                                os.println("[busy]");
                                flag = true;
                            }
                        }
                    }
                    os.println("[nonbusy]");
                }

⌨️ 快捷键说明

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