正在尝试从Spring TCP Client连接到Java TCP Server。 从Spring TCP Client发送请求。 Java TCP Server向Spring TCP Client发送回复。 服务器代码:
public static void main(String args[]) throws IOException, ClassNotFoundException
{
server = new ServerSocket(port);
while (true)
{
Socket socket = server.accept();
InputStream ois = socket.getInputStream();
System.out.println(new Timestamp(System.currentTimeMillis()));
String message = convert(ois, Charset.defaultCharset());
System.out.println("Message Received: " + message);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Hello World");
ois.close();
os.close();
socket.close();
if (message.equalsIgnoreCase("exit"))
break;
}
System.out.println("Shutting down Socket server!!");
server.close();
}
public static String convert(InputStream inputStream, Charset charset) throws IOException
{
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset)))
{
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
Spring TCP Client XML:
<int:channel id="input" />
<int:channel id="output" />
<int-ip:tcp-outbound-gateway id="outgateway" request-channel="input" reply-channel="clientBytes2StringChannel" connection-factory="client" reply-timeout="5000000"
request-timeout="500000"
></int-ip:tcp-outbound-gateway>
<int:object-to-string-transformer id="clientBytes2String" input-channel="clientBytes2StringChannel" />
Spring TCP客户端代码:
public class EchoService
{
public String receive(String input)
{
return "echo :" + input;
}
}
public interface SimpleGateway
{
public String send(String text);
}
public class Main
{
public static void main(String args[])
{
final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("Client.xml");
SimpleGateway gateway = applicationContext.getBean(SimpleGateway.class);
try
{
System.out.println("Waiting for Server to Accept Connections");
String reply = null;
reply = gateway.send("hello");
System.out.println("My Reply" + reply);
}
catch (MessagingException exc)
{
System.out.println("Exception occurred : Timed out --" + exc);
}
}
}
从TCP客户端接收以下错误
failedMessage=GenericMessage [payload=hello, headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@1b4c3a9, errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@1b4c3a9, id=7c8a9096-c08a-ed6b-b6d6-9874a66bd036, timestamp=1548304570325}]
服务器套接字需要更多时间来处理消息。因此,客户端关闭连接服务器套接字pgm会引发以下错误
Exception in thread "main" java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Unknown Source)
at com.tcs.bancs.CMI.incomingInterfaces.TestPgm.main(TestPgm.java:42)