I am trying to pass a json from C# server to Java server using TCP, problem is that the first time Java server seems to receive an empty json. Second time and onwards it works fine, see output bellow. Any ideas or suggestions are welcome, thanks in advance.
Output:
Starting server...
Waiting for a connection..
Connected!
Reading...
Received empty object
Received:
Connected!
Reading...
Received: "Request:gethotellist"
Connected!
Reading...
Received: "Request:gethotellist"
Here is the C# code snippet for sending json:
public void GetHotelList()
{
TcpClient clientSocket = new TcpClient();
clientSocket.Connect("127.0.0.1", 6767);
NetworkStream ns = clientSocket.GetStream();
string jsonRequest = "Request:gethotellist";
string jsonToSend = JsonConvert.SerializeObject(jsonRequest);
byte[] dataBytes = Encoding.UTF8.GetBytes(jsonToSend);
ns.Write(dataBytes, 0, dataBytes.Length);
ns.Close();
}
Java server:
public class JHotelServer
{
public static void main(String[] args) throws IOException
{
final int PORT = 6767;
System.out.println("Starting server...");
@SuppressWarnings("resource")
ServerSocket welcomeSocket = new ServerSocket(PORT);
System.out.println("Waiting for a connection..");
while(true)
{
try
{
Socket connectionSocket = welcomeSocket.accept();
System.out.println("Connected!");
Thread connectionThread = new Thread(new TcpConnectionManager(connectionSocket));
connectionThread.start();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
And here is the Tcp Communication manager:
public class TcpConnectionManager implements Runnable
{
private DataInputStream inFromDotNet;
public TcpConnectionManager(Socket socket) throws IOException
{
inFromDotNet = new DataInputStream(socket.getInputStream());
}
@Override
public void run()
{
try
{
System.out.println("Reading...");
byte[] rvdMsgByte = new byte[inFromDotNet.available()];
// Collecting data into byte array
for (int i = 0; i < rvdMsgByte.length; i++)
{
rvdMsgByte[i] = inFromDotNet.readByte();
}
if (rvdMsgByte.length == 0)
{
System.out.println("Received empty object");
}
// Converting collected data in byte array into String.
String rvdMsgTxt = new String(rvdMsgByte);
System.out.println("Received: " + rvdMsgTxt);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}