📄 chatserver.java
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -