springboot 集成socket,實現客戶端服務端通信


服務端:
@Data
@Component
public class DelongServerSocket {
@Value("${socket.port}")
private Integer port;
private boolean started;
private ServerSocket ss;
public static ConcurrentHashMap<String, ClientSocket> clientsMap = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newCachedThreadPool();

public static void main(String[] args) {
System.out.println("進入main:");
new DelongServerSocket().start(10086);
}

public void start() {
start(null);
}

public void start(Integer port) {
try {
ss = new ServerSocket(port == null ? this.port : port);
started = true;
System.out.println("端口已開啟,占用端口號...."+this.port);
} catch (Exception e) {
System.out.println("端口使用中....");
System.out.println("請關掉相關程序並重新運行服務器!");
e.printStackTrace();
System.exit(0);
}
int count = 0;
try {
while (started) {
Socket socket = ss.accept();
socket.setKeepAlive(true);
count++;
ClientSocket register = ClientSocket.register(socket,count);
System.out.println("a client connected!");
if (register != null) {
executorService.submit(register);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

客戶端線程:
@Data
@Slf4j
public class ClientSocket implements Runnable {

private Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private String key;
private String message;

/**
* 注冊socket到map里
*
* @param socket
* @return
*/
public static ClientSocket register(Socket socket,int count) throws Exception {
ClientSocket client = new ClientSocket();
try {
client.setSocket(socket);
client.setInputStream(new DataInputStream(socket.getInputStream()));
client.setOutputStream(new DataOutputStream(socket.getOutputStream()));
System.out.println("客戶端的IP:"+socket.getInetAddress().getHostAddress());
System.out.println("user" + count+"正在登錄...");
client.setKey("user"+count);
DelongServerSocket.clientsMap.put(client.getKey(), client);
System.out.println(DelongServerSocket.clientsMap);
return client;
} catch (Exception e) {
client.logout();
}
return null;
}

/**
* 發送數據
*
* @param str
*/
public void send(String str) throws Exception {
System.out.println("服務端發送:======" + str);
try {
outputStream.write(str.getBytes());
} catch (Exception e) {
logout();
}
}

/**
* 接收數據
*
* @return
* @throws Exception
*/
public String receive() throws Exception {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String info = new String(bytes, "utf-8");
System.out.println("服務端接收:===" + info);
return info;
} catch (Exception e) {
logout();
}
return null;
}

/**
* 登出操作, 關閉各種流
*/
public void logout() throws Exception {
if (DelongServerSocket.clientsMap.containsKey(key)) {
DelongServerSocket.clientsMap.remove(key);
}

System.out.println(DelongServerSocket.clientsMap);
try {
// socket.shutdownOutput();
// socket.shutdownInput();
inputStream.close();
outputStream.close();
} catch (Exception e) {
throw new Exception("關閉輸入輸出異常", e);
} finally {
try {
socket.close();
} catch (Exception e) {
throw new Exception("關閉socket異常", e);
}
}
}

/**
* 發送數據包, 判斷數據連接狀態
*
* @return
*/
public boolean isSocketClosed() {
try {
//socket.sendUrgentData(1);
//發送
Socket socket1 = DelongServerSocket.clientsMap.get("user1").getSocket();
socket1.getOutputStream().write("測試1".getBytes(StandardCharsets.UTF_8));
//socket.getOutputStream().write("測試".getBytes(StandardCharsets.UTF_8));
//接收
byte[] bytes = new byte[1024];
socket.getInputStream().read(bytes);
String receive = new String(bytes, "utf-8");
System.out.println("服務端接收消息" + receive);
return false;
} catch (Exception e) {
return true;
}
}

@Override
public void run() {
// 每過5秒連接一次客戶端
while (true) {
try {
TimeUnit.SECONDS.sleep(5);
if (isSocketClosed()) {
System.out.println("關閉");
logout();
break;
}
} catch (Exception e) {
e.printStackTrace();
}

}

}

@Override
public String toString() {
return "Client{" +
"socket=" + socket +
", inputStream=" + inputStream +
", outputStream=" + outputStream +
", key='" + key + '\'' +
'}';
}

}

客戶端1:
public class ChatClient {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8082;
// 與服務端建立連接
Socket socket = new Socket(host, port);
socket.setOOBInline(true);
// 建立連接后獲得輸出流
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
int i=0;
while (true) {
send("客戶端測試"+i,outputStream);
receive(inputStream);
i++;
}
}

/**
* 發送數據
*
* @param str
*/
public static void send(String str,DataOutputStream outputStream) throws Exception {
System.out.println("客戶端發送:======"+str);
try {
outputStream.write(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 接收數據
*
* @return
* @throws Exception
*/
public static String receive(DataInputStream inputStream) throws Exception {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String info = new String(bytes, "utf-8");
System.out.println("客戶端接收:==="+info);
return info;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}

客戶端2:
public class ChatClient2 {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8082;
// 與服務端建立連接
Socket socket = new Socket(host, port);
socket.setOOBInline(true);
// 建立連接后獲得輸出流
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
int i=0;
while (true) {
send("客戶端2測試"+i,outputStream);
//receive(inputStream);
i++;
}
}

/**
* 發送數據
*
* @param str
*/
public static void send(String str,DataOutputStream outputStream) throws Exception {
System.out.println("客戶端發送:======"+str);
try {
outputStream.write(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 接收數據
*
* @return
* @throws Exception
*/
public static String receive(DataInputStream inputStream) throws Exception {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String info = new String(bytes, "utf-8");
System.out.println("客戶端接收:==="+info);
return info;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}


服務端啟動:

@SpringBootApplication
@Controller
public class DemoApplication {

public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
context.getBean(DelongServerSocket.class).start();

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM