我正在使用Spring Boot Web开发Web应用程序,并且想使用IP和端口(连接,发送,接收和断开连接)与TCP套接字服务器进行通信。
我是Spring Boot的新手,我在互联网上搜索了许多天而没有任何工作结果,因此Websocket解决方案在这种情况下将无法工作。
更新(请确认) 我认为我可以像其他Java程序一样在Spring Boot Web中使用标准的java.io. *和java.net。*:
try {
try (Socket clientSocket = new Socket(IP, PORT);
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()))) {
System.out.println("Connected to server");
String str = "test";
out.write(str);
out.flush();
char[] cbuf = new char[size];
br.read(cbuf, 0, size);
System.out.println(cbuf);
}
} catch (IOException ex) {
ex.printStackTrace();
}
答案 0 :(得分:0)
这是我自己为SpringBoot开发的简单tcp客户端的版本。
首先,您必须使用openConnection()方法打开连接。然后,您可以使用sendMessage()方法发送消息,并使用takeMessage()方法接收消息。
@Service("socketClient")
public class SocketClient {
@Value("brain.connection.port")
int tcpPort;
@Value("brain.connection.ip")
String ipConnection;
private Socket clientSocket;
private DataOutputStream outToTCP;
private BufferedReader inFromTCP;
private PriorityBlockingQueue<String> incomingMessages = new PriorityBlockingQueue<>();
private PriorityBlockingQueue<String> outcomingMessages = new PriorityBlockingQueue<>();
private final Logger log = LoggerFactory.getLogger(this.getClass());
private Thread sendDataToTCP = new Thread(){
public void run(){
String sentence = "";
log.info("Starting Backend -> TCP communication thread");
while(true){
try {
sentence = incomingMessages.take();
outToTCP.writeBytes(sentence + '\n');
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
private Thread getDataFromTCP = new Thread(){
public void run(){
log.info("Starting TCP -> Backend communication thread");
while(true){
String response = "";
try {
response = inFromTCP.readLine();
if (response == null)
break;
outcomingMessages.put(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public void openConnection(){
try {
this.clientSocket = new Socket(ipConnection, tcpPort);
outToTCP = new DataOutputStream(clientSocket.getOutputStream());
inFromTCP = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
getDataFromTCP.start();
sendDataToTCP.start();
} catch (IOException e) {
e.printStackTrace();
}
}
//Send messages to Socket.
public void sendMessage(String message) throws InterruptedException {
incomingMessages.put(message);
}
//Take Message from Socket
public String takeMessage() throws InterruptedException {
return outcomingMessages.take();
}
}