multichatserverdemo.java

来自「java实现ftp功能。其中含有一个监听端口并提供HTML文档的程序.内容」· Java 代码 · 共 65 行

JAVA
65
字号
import java.net.*;
import java.io.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MultiChatServerDemo{ 
	public static void main(String args[]){
		ServerSocket serverSocket=null;
		try{
			serverSocket=new ServerSocket(1111);
		}catch(Exception e){
			System.out.println("Error"+e);
			System.exit(1);
		}
		while(true){
			Socket clientSocket=null;
			System.out.println("waiting for users...");
			try	{
				clientSocket=serverSocket.accept();
			}catch(IOException e){
				System.out.println("accept failed:"+e);
			}
			new ServerThread(clientSocket).start();
		}
	}
} 

class ServerThread extends Thread{
	DataInputStream input;
	PrintStream output;
	String user;
	Socket clientSocket;
	
	ServerThread(Socket clientSocket){
		this.clientSocket=clientSocket;
	}
	
	public void run(){
		try{
			input=new DataInputStream(
				clientSocket.getInputStream());
			output=System.out;
			user=input.readLine();
			System.out.println(user+" Connected!");
		}catch(IOException e){ }
		try {
			while(true){
				String string;
				if((string=input.readLine())==null)
					break;
				output.println(user+string);
				output.flush();
			}
		}catch(Exception e){
			return;
		}		
		System.out.println(user+ "has disconnected.");
		try{
			clientSocket.close();
			input.close();
		}catch(Exception e){
			return;
		}
	}
}

⌨️ 快捷键说明

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