Java Socket Server and Client Socket c# issue - c#

i have a problem comunicating with a java server socket with my client c# socket.
The problem came from when i try to read the response. My code is this:
IPHostEntry IPHost = Dns.Resolve("IP_ADDRESS");
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
Console.WriteLine(addr[0]);
EndPoint ep = new IPEndPoint(addr[0],1024);
Socket sock =
new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Connect(ep);
if(sock.Connected)
Console.WriteLine("OK");
Encoding ASCII = Encoding.ASCII;
string Get = "A";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
sock.Send(ByteGet, ByteGet.Length, 0);
Int32 bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
Console.WriteLine(bytes);
String strRetPage = null;
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
while( bytes > 0 ) {
bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
Console.WriteLine(strRetPage );
}
sock.Close();
at the code line
Int32 bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0);
my client hang.
I have to stop the application. It seems that don't respond the socket server.
The specific of the socket server is to send and receive a BitStream.

Without the Java code of your server it's hard to tell, but it seems very likely your server is not sending the expected 256 bytes. Since Socket.Receive is blocking by default the client keeps waiting for data.

Related

Server client communication using Socket C#

I have created an application, which is communicating a server using IP/port. It is sending a ISO request string(Bitmaps in ASCII format) and receiving a response string same format. While Sending the bytes through socket.send and receiving the bytes in socket.receive method. I can see extended ASCII characters are getting changed on other side (Server side/Clint side). I am using below code. Can anyone suggest please, How to resolve the issue.
IPAddress ipAddr = IPAddress.Parse("10.03.0.18");
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 12345);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket sender = new Socket(ipAddr.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
sender.Connect(localEndPoint);
string requeststring = AccountValidationRequest();
byte[] messageSent = Encoding.ASCII.GetBytes(requeststring);
int byteSent = sender.Send(messageSent);
byte[] ServerResponse = new byte[1024];
int byteRecv = sender.Receive(ServerResponse);
string ISO8583Message = Encoding.ASCII.GetString(ServerResponse, 0, byteRecv);
Console.WriteLine("Response received from server: --> :{0}", Encoding.ASCII.GetString(ServerResponse, 0, byteRecv));
As it was suggested in comments you should assert that you read all data, not only the first chunk.
Byte[] bytesReceived = new Byte[256];
int bytes = 0;
var ISO8583Message = "Response: \n";
do {
bytes = sender.Receive(bytesReceived, bytesReceived.Length, 0);
ISO8583Message = ISO8583Message + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);
There are some nice examples with using sockets on https://learn.microsoft.com/pl-pl/dotnet/api/system.net.sockets.socket?view=netframework-4.8.

TCP Server gets ???????? instead of the real message

The server is written in c# and works correctly with a client I made in c#, now i'm trying to make an android client but the server doesn't get the real message, it gets just a lot of question marks.
Here is the server
TcpListener listen = new TcpListener(IPAddress.Any, 1200);
TcpClient client;
listen.Start();
client = listen.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
string message = Encoding.Unicode.GetString(buffer, 0, data);
Console.WriteLine(message);
this is the Android client
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString()
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
For example if I send the message "Hello", the server prints "???????????" and it happens the same for any message I send, even just 1 letter
I also tried with different methods like this one but the result is the same:
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(str);
Change:
string message = Encoding.Unicode.GetString(buffer, 0, data);
into:
string message = Encoding.UTF8.GetString(buffer, 0, data);
Try also UTF16. I think java uses this encoding now.

Stopping communication in client server using c#

I am trying to make a client server communication using c# .I have made the client and the server to communicate with each other. But, the problem I am facing is that how do I stop the communication?
Condition: The server should always be listening (when multiple clients are present.) (presently, I am using single client). The client should have a stop or exit condition (ie; when the client sends "exit" the client should terminate, the server should still be listening to other clients) when it finishes transmitting the data.
I am new to c#. Tried searching on google also. but didn't find what I need.
Part of my code:
Server:
try
{
IPAddress addr = IPAddress.Parse("127.0.0.1");
string a = "recieved by server";
TcpListener Receiver = new TcpListener(addr, 1234);
Receiver.Start();
Console.WriteLine("trying to connect to " + addr);
Socket s = Receiver.AcceptSocket();
Console.WriteLine("Connected");
while (true)
{
byte[] b = new byte[100];
int k = s.Receive(b);
char[] chars = new char[b.Length / sizeof(char)];
System.Buffer.BlockCopy(b, 0, chars, 0, b.Length);
string dataReceived = new string(chars);
Console.WriteLine(dataReceived);
byte[] bw = new byte[a.Length * sizeof(char)];
System.Buffer.BlockCopy(a.ToCharArray(), 0, bw, 0, bw.Length);
Console.WriteLine("sending Acknowledgement to client");
s.Send(bw);
}
//Receiver.Stop();
}
Client:
try
{
TcpClient TcpC = new TcpClient();
TcpC.Connect("127.0.0.1", 1234);
while (true)
{
Console.WriteLine("enter somethiong to send");
String s = Console.ReadLine();
NetworkStream CStream = TcpC.GetStream();
byte[] bw = new byte[s.Length * sizeof(char)];
System.Buffer.BlockCopy(s.ToCharArray(), 0, bw, 0, bw.Length);
Console.WriteLine("Transmit");
CStream.Write(bw, 0, bw.Length);
if (s == "exit")
{
CStream.Flush();
CStream.Close();
TcpC.Close();
break;
}
byte[] br = new byte[100];
int k = CStream.Read(br, 0, 100);
char[] chars = new char[br.Length / sizeof(char)];
System.Buffer.BlockCopy(br, 0, chars, 0, br.Length);
string ackReceived = new string(chars);
Console.WriteLine(ackReceived);
}
//TcpC.Close();
}
Once you accepted socket connection from the client using Socket s = Receiver.AcceptSocket(); you need to put your commands processing logic in your while (true) { } block in some another thread (using a Task or Thread whatever), and then you should start accepting new socket connection using Receiver.AcceptSocket(); again.
The problem is you do a
Receiver.Stop();
when it should be the socket you are closing.
The idea is you create a new socket to handle each time a client connects - and that's the connection one you terminate, not the main listening socket.
There is good sample code here:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx

async tcp connection C#

TcpListener tcpServer = new TcpListener(8080);
tcpServer.Start();
tcpServer.BeginAcceptTcpClient(new AsyncCallback(this.messageRecived), tcpServer);
I have some code for accept reading from tcp client, client send massage in this way:
TcpClient client = new TcpClient("192.168.0.2", 8080)
string Str = "it's work";
byte[] Buffer = Encoding.ASCII.GetBytes(Str);
client.GetStream().Write(Buffer, 0, Buffer.Length);
the problem is in messageRecived method:
public void messageRecived(IAsyncResult result)
{
byte[] data = new byte[20000];
string outData;
TcpListener server = (TcpListener)result.AsyncState;
server.AcceptTcpClient().GetStream().Read(data, 0, server.Server.ReceiveBufferSize);
outData = Encoding.ASCII.GetString(data);
addLog(outData);
}
When i send message to server the method received run until to this line:
server.AcceptTcpClient().GetStream().Read(data, 0, server.Server.ReceiveBufferSize);
and in the next iteration it begin from next line to the end of method. What is the problem?
probably because you are not closing stream from client, please refer to below link to properly dispose stream from client
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx
Try to flush the client Stream.
TcpClient client = new TcpClient("192.168.0.2", 8080)
string Str = "it's work";
byte[] Buffer = Encoding.ASCII.GetBytes(Str);
var stream = client.GetStream()
stream.Write(Buffer, 0, Buffer.Length);
stream.Flush()

Sending long XML over TCP

I'm sending an object (class name House) over TCP using the TcpListener on the server side in response to any message received from the TcpClient.
When the message is received, it is currently populating a text box named textBox1.
If I send a line of text, it works fine. You'll notice that I have a redundant line "Hello, I'm a server" for testing this purpose. But when I send the XML, it is cutting it off prematurely.
When I send serialised XML in to the stream, I'm also receiving this error from the server side:
Unable to read data from the transport connection: An existing
connection was forcibly closed by the remote host.
Here's my server code
// Set the variables for the TCP listener
Int32 port = 14000;
IPAddress ipaddress = IPAddress.Parse("132.147.160.198");
TcpListener houseServer = null;
// Create IPEndpoint for connection
IPEndPoint ipend = new IPEndPoint(ipaddress, port);
// Set the server parameters
houseServer = new TcpListener(port);
// Start listening for clients connecting
houseServer.Start();
// Buffer for reading the data received from the client
Byte[] bytes = new Byte[256];
String data = "hello, this is a house";
// Show that the TCP Listener has been initialised
Console.WriteLine("We have a TCP Listener, waiting for a connection...");
// Continuing loop looking for
while (true)
{
// Create a house to send
House houseToSendToClient = new House
{
house_id = 1,
house_number = 13,
street = "Barton Grange",
house_town = "Lancaster",
postcode = "LA1 2BP"
};
// Get the object serialised
var xmlSerializer = new XmlSerializer(typeof(House));
using (var memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, houseToSendToClient);
}
// Accept an incoming request from the client
TcpClient client = houseServer.AcceptTcpClient();
// Show that there is a client connected
//Console.WriteLine("Client connected!");
// Get the message that was sent by the server
NetworkStream stream = client.GetStream();
// Blank int
int i;
// Loop for receiving the connection from the client
// >>> ERROR IS ON THIS LINE <<<
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
Console.WriteLine("here");
// Take bytes and convert to ASCII string
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received s, return house");
// Convert the string to a byte array, ready for sending
Byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes("Hello, I'm a server");
// Send the data back to the client
//stream.Write(dataToSend, 0, dataToSend.Length);
// Send serialised XML in to the stream
xmlSerializer.Serialize(stream, houseToSendToClient);
}
// Close the connection
client.Close();
}
Client code
// Get the object serialised
var xmlSerializer = new XmlSerializer(typeof(House));
// Set the variables for the TCP client
Int32 port = 14000;
IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipend = new IPEndPoint(ipaddress, port);
string message = "s";
try
{
// Create TCPCLient
//TcpClient client = new TcpClient("localhost", port);
TcpClient client = new TcpClient();
// Convert the string to a byte array, ready for sending
Byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes(message);
// Connect using TcpClient
client.Connect(ipaddress, port);
// Client stream for reading and writing to server
NetworkStream stream = client.GetStream();
// Send the data to the TCP Server
stream.Write(dataToSend, 0, dataToSend.Length);
//xmlSerializer.Serialize(stream, houseToSend);
// Buffer to store response
Byte[] responseBytes = new Byte[256];
string responseData = String.Empty;
// Read the response back from the server
Int32 bytes = stream.Read(responseBytes, 0, responseBytes.Length);
responseData = System.Text.Encoding.ASCII.GetString(responseBytes, 0, bytes);
textBox1.Text = responseData;
// Close the stream and the client connection
stream.Close();
client.Close();
}
catch (SocketException e)
{
MessageBox.Show(e.ToString());
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
I've marked on the code where the error is appearing.
Is it because the message is too long?
Your client code is assuming that the entire message will come through in one call to the Read(...) method, which is absolutely wrong. From the MSDN docs: "An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached."
It's possible that, for a 1024-byte XML document, you may have to call Read(...) 1024 times to get the entire message.
Really, you'd do well to send a four-byte length before you send the XML, so that the client knows how much data to expect. The client will read four bytes, convert that to an integer length, then read that many more bytes, then turn those bytes into XML.

Categories