package com.hirain.pmtsd.tcp.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class TCP {
//监听端口
private static final int PORT = 1234;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
try {
//建立服务器的Socket,并设定一个监听的端口PORT
serverSocket = new ServerSocket(PORT);
System.out.println("开始建立连接");
while(true){
try {
socket = serverSocket.accept();
System.out.println("连接成功");
} catch (Exception e) {
System.out.println("建立与客户端的连接出现异常");
e.printStackTrace();
}
ServerThread thread = new ServerThread(socket);
thread.start();
}
} catch (Exception e) {
System.out.println("端口被占用");
e.printStackTrace();
}
finally {
serverSocket.close();
}
}
}
class ServerThread extends Thread {
private Socket socket ;
InputStream inputStream;
OutputStream outputStream;
ConcurrentHashMap<String, HashMap<String, Object>> m = new ConcurrentHashMap<>();
HashMap<String, Object> map =new HashMap<>();
//public Gson gson =new Gson();
public ServerThread(Socket socket){
this.socket=socket;
}
public void run(){
try {
while (true){
//接收客户端的消息并打印
System.out.println(socket);
inputStream=socket.getInputStream();
socket.getInetAddress();
byte[] by = new byte[1024];
inputStream.read(by);
String string1 = new String(by).trim();
String string = new String(string1.getBytes("GBK"),"UTF-8");
System.out.println(string);
//byte[] bytes = Run.map.toString().getBytes();
/* for(ConcurrentHashMap.Entry<String, HashMap<String,Object>> map2: Run.map.entrySet())
{
if (string.equals("CAircraft")) {
map.put("fAltitude_AGL", map2.getValue().get("fAltitude_AGL"));
map.put("dLatitude", map2.getValue().get("dLatitude"));
map.put("dLongitude", map2.getValue().get("dLongitude"));
m.put("CAircraft", map);
}
TestClient testClient =new TestClient("",8080);
testClient.sendMessage(string);
}
String message = gson.toJson(m);*/
//向客户端发送消息
String message = "{"红方":{"速度":"260"}}";
//String message = "";
outputStream = socket.getOutputStream();
//Integer s = message.getBytes().length;
//String num = s.toString();
//outputStream.write(string.getBytes());
System.out.println(message.getBytes().length);
outputStream.write(message.getBytes());
System.out.println("OK");
}
} catch (Exception e) {
System.out.println("客户端主动断开连接了");
//e.printStackTrace();
}
//操作结束,关闭socket
try{
socket.close();
}catch(IOException e){
System.out.println("关闭连接出现异常");
e.printStackTrace();
}
}
}