i plan to write a Java TCP Server and a Client in C# .NET. I take Java for the Server because i have the ability to run the Server on Linux. My Problem is that the .NET Client can Connect to the Server but if i send something to the Server, the Server doesn´t receive anything.
Here is my Client:
static void Main(string[] args)
{
try
{
System.Net.Sockets.TcpClient tcpclnt = new System.Net.Sockets.TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.178.26", 1337);
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
stm.Flush();
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
And here is my Server:
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket socket = new ServerSocket(1337);
while(true)
{
System.out.println("... Server gestartet");
Socket connectionSocket = socket.accept();
BufferedReader inputFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
System.out.println(connectionSocket.getRemoteSocketAddress());
DataOutputStream outputStream = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inputFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + "\n";
outputStream.writeBytes(capitalizedSentence);
}
}
The code i tested is only a Prototyp for Testing the connection to the Java Server. I also plan to communicate with the Java Tcp Server with iOS and maybe Windows Phone. So i hope anyone of you have an answer for me.
Your client sends the bytes of a line, and waits for a response, keeping the stream open.
Your server waits for a line break (or the end of the stream, i.e. the connection being closed) before ReadLine
returns. So both sides are waiting for the other.
I would suggest that you use an OutputStreamWriter
wrapped around the stream on the client side - then you can use WriteLine
very simply (rather than messing around with the encoding yourself). When the server sees the line break, it will respond. I'd also use an InputStreamReader
on the client rather than calling Convert.ToChar
on each byte. Fundamentally, if you're only interested in transferring text and you're happy to use "a line" as the unit of messaging, using a writer/reader pair on both sides is the simplest approach.
See more on this question at Stackoverflow