📄 tankserver.java
字号:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class TankServer {
private static int ID = 100;
public static final int TCP_PORT = 8888;
List<Client> clients = new ArrayList<Client>();
public void start() {
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_PORT);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
Socket s = null;
try {
s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String IP = s.getInetAddress().getHostAddress();
int udpPort = dis.readInt();
Client c = new Client(IP, udpPort);
clients.add(c);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeInt(ID++);
s.close();
System.out.println("A Client Connect! Addr- " + s.getInetAddress() + ":" + s.getPort() + "----UDP Port:" + udpPort);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(s != null) {
try {
s.close();
s = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new TankServer().start();
}
private class Client {
String IP;
int udpPort;
public Client(String IP, int udpPort) {
this.IP = IP;
this.udpPort = udpPort;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -