[英]Sending more than 1 message to TCP server in same connection
我已經在Java中創建了一個TCP服務器,在Ruby中創建了一個TCP客戶端。 問題是我無法在同一連接中發送多個消息,僅發送第一個消息而沒有發送其他消息。
這是Java代碼
package com.roun512.tcpserver;
import java.io.*;
import java.net.*;
public class Program {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while(true)
{
Socket connection = Socket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
這是客戶端代碼
Client.rb
require 'socket'
class Client
def initialize()
server = TCPSocket.open("127.0.0.1", 6789)
if server.nil?
puts "error"
else
puts "connected"
end
server.puts("Hello\r\n")
sleep 2
server.puts("There\r\n")
server.close
end
end
Client.new()
我只收到Hello
。 我嘗試了許多其他方法,但是都沒有用。
所以我的問題是如何在單個連接中發送多個消息,任何幫助將不勝感激:)
提前致謝!
Socket.accept()
在讀取第一行之后等待新的連接。 請嘗試以下操作:
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while (true)
{
Socket connection = Socket.accept();
while(true)
{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
如果可行, while (true)
更改為有意義的條件,並且不要在工作完成后關閉連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.