chatserver.java

来自「JAVA程序设计简单语音聊天源码」· Java 代码 · 共 77 行

JAVA
77
字号
import java.io.DataInputStream;
import java.io.IOException;
import java.net.*;


public class ChatServer {
	
	boolean started = false;
	boolean bConnected = false;
	
	
	public static void main(String[] args) {
		new ChatServer().begin();
	}
	
	public void begin(){				
		ServerSocket ss = null;
		
		try{
			ss = new ServerSocket(5000);
		}catch (BindException e){
			System.out.println("端口正在使用中,请将相关程序关掉!");
		}catch(IOException e){
			e.printStackTrace();
		}
		
		try{
			if (ss !=null ) started = true;
			while(started){
				Socket s = ss.accept();
				System.out.println("a client connected!");
				new Thread(new Client(s)).start();
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	private class Client implements Runnable{
		DataInputStream dis = null;
		Socket s = null;
		
		public Client(Socket s){
			this.s = s;
			bConnected = true;
			try{
			dis = new DataInputStream(s.getInputStream());
			}catch(IOException e){
				e.printStackTrace();
				
			}
		}
		
		public void run() {
		try{	
			while (bConnected){
				String str =dis.readUTF();
				System.out.println(str);
			}
		}catch (SocketException e){
			System.out.println("Client closed!");
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				if (dis != null)dis.close();
				if (s !=null)s.close();
			}catch (IOException e){
				e.printStackTrace();
			}
		}
		}
		
	}
	
}

⌨️ 快捷键说明

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