Receive Raw HEX by socket and convert to string - c#

I have the following problem, I try to receive raw HEX value from a TCP/IP socket and write them down in a txt file, Only I am having some problems converting this raw HEX data to a UTF-8 string. I am using the following method:
TcpClient client = new TcpClient("192.168.200.91", 2101);
NetworkStream netStream = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
netStream.Read(bytes, 0, (int)client.ReceiveBufferSize);
string returndata = Encoding.UTF8.GetString(bytes);
using (var writer = new StreamWriter(#"C:\Users\ -\Documents\test.txt", false, Encoding.UTF8))
{
writer.WriteLine(returndata);
}
This returns : *þý% ˆ ꇅ ÿ Œ7ºe B %û
How to successfully read the raw HEX data and convert this into a readable string?

Use BitConverter:
TcpClient client = new TcpClient("192.168.200.91", 2101);
NetworkStream netStream = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
int bytesRead = netStream.Read(bytes, 0, (int)client.ReceiveBufferSize);
string returndata = BitConverter.ToString(bytes, 0, bytesRead).Replace("-", "")
using (var writer = new StreamWriter(#"C:\Users\ -\Documents\test.txt", false, Encoding.UTF8))
{
writer.WriteLine(returndata);
}

Related

Getting Response from telnet C# tcpclient

I've been browsing for answers regarding my concern but I can't find concrete answers or at least clear thoughts on getting a response from Telnet connection. Here is my code:
TcpClient vpnMI = new TcpClient("127.0.0.1", 7505);
String message = "hold release\n";
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = vpnMI.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent {0}", message);
data = new Byte[256];
MemoryStream memoryStream = new MemoryStream();
String responseData = String.Empty;
Int32 bytes = 0;
do
{
bytes = stream.Read(data, 0, data.Length);
memoryStream.Write(data, 0, bytes);
}
while (stream.DataAvailable);
responseData = System.Text.Encoding.ASCII.GetString(memoryStream.ToArray());
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
vpnMI.Close();
But I can only get the response before the "hold release" was sent even though there is a response after.
Thank you in advance for the response.
I am using this piece of code, you can take a look if this help:
public async Task<string> SendMessageAsync(string host, int port, string message, string encoding = "utf-8")
{
using (var tcpClient = new TcpClient())
{
//connect
await tcpClient.ConnectAsync(host, port);
using (NetworkStream networkStream = tcpClient.GetStream())
{
//write message to stream
var enc = Encoding.GetEncoding(encoding);
var bytes = enc.GetBytes(message);
await networkStream.WriteAsync(bytes, 0, bytes.Length);
//read response from stream
var buffer = new byte[READ_BUFFER_SIZE];
using (var ms = new MemoryStream())
{
//read all bytes to ms
while (true)
{
int byteCount = await networkStream.ReadAsync(buffer, 0, READ_BUFFER_SIZE);
ms.Write(buffer, 0, byteCount);
if (byteCount < READ_BUFFER_SIZE)
{
break;
}
}
//convert ms to string
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms, enc))
{
var result = await sr.ReadToEndAsync();
return result;
}
}
}
}
}
networkStream.ReadAsync() returns the count of bytes that actually read from stream, if this count is less than the count you're trying to read, that's the last part.

network connection between "nornal" C# and UWP

I try to get a connection between an UWP-programm and a "normal" C# application.
UWP:
StreamSocket s = new StreamSocket();
await socket.ConnectAsync(new HostName("localhost"), "8003");
BinaryWriter bw = new BinaryWriter(socket.OutputStream.AsStreamForWrite());
String toSend = "Hello World!";
byte[] text = Encoding.UTF8.GetBytes(toSend);
byte[] number = BitConverter.getBytes(text.Length);
if(BitConverter.isLittleEndian) Array.Reverse(number);
bw.Write(number, 0, number.Length);
bw.Write(text, 0, text.Length);
"normal" C#, after the TcpListener etablished a new ClientThread:
//client was accepted by the server and is an instance of TcpClient
BinaryReader br = new BinaryReader(client.GetStream());
byte[] number = new byte[4];
br.Read(number, 0, number.Length);
if(BitConverter.isLittleEndian) Array.Reverse(number);
int size = BitConverter.ToInt32(number);
byte[] buffer = new byte[size];
br.Read(buffer, 0, buffer.Length);
String recieved = Encoding.UTF8.GetString(buffer);
Debug.WriteLine(recieved);
But the server doesn´t recieves anything. And the int size is 0. But if i run the UWP-code on a "normal" C# application, by replacing the s.OutputStream.AsStreamForWrite() with client.GetStream() and using a TcpClient instead of an StreamSocket the server recieves the text. What am I doing wrong?
Greets Marcel

Getting junk values while converting network stream to string

I am using Telnet protocol in order to read a text file from the server PC. But when I try to convert network stream to sting, it is giving some junk values. What will be the issue here?
NetworkStream ns = tcpclient.GetStream();
StreamReader streamReader = new StreamReader(ns);
StreamWriter streamWriter = new StreamWriter(ns);
byte[] bytes = new byte[tcpclient.ReceiveBufferSize];
int bytesread = tcpclient.ReceiveBufferSize;
ns.Read(bytes, 0, bytesread);
string returndata = Encoding.ASCII.GetString(bytes);
I have tried to read the text file through command prompt. Using the following steps
1. Enabled telnet server in the server pc and client in my pc.
2. change telnet port in server pc to 24
3. Using telnet command connect to server pc.
4. from telnet window> using type display the content of the text file in command prompt.
Now I want to do the same from my c# code. I have written the following code:
TcpClient tcpclient = new TcpClient();
tcpclient.Connect(<ip address>, <port>);
NetworkStream ns = tcpclient.GetStream();
StreamReader streamReader = new StreamReader(ns);
byte[] msg = Encoding.ASCII.GetBytes("type <file location>");
string returnd = Encoding.ASCII.GetString(msg);
ns.Write(msg, 0, msg.Length);
StreamWriter streamWriter = new St
byte[] bytes = new byte[tcpclient.ReceiveBufferSize];
int bytesread = tcpclient.ReceiveBufferSize;
ns.Read(bytes, 0, bytesread);reamWriter(ns);
string returndata = Encoding.ASCII.GetString(bytes);
but my code is always giving some junk output like " ÿý%ÿûÿûÿý'ÿýÿý"
ReceiveBufferSize is the size of the receive buffer, but when you read, you don't always get a full buffer. The Read method returns the actual number of bytes that were read, you should use that to limit the part of the buffer you want to decode:
byte[] bytes = new byte[tcpclient.ReceiveBufferSize];
int nRead = ns.Read(bytes, 0, tcpclient.ReceiveBufferSize);
string returndata = Encoding.ASCII.GetString(bytes, nRead);

C# read all bytes

I am trying to write a simple client/server application in C#. The following is an example server reply sent to my client:
reply {20}<entry name="test"/>
where {20} indicates number of chars that full reply contains.
In the code I wrote below how can I use this number to loop and read ALL chars?
TcpClient tcpClient = new TcpClient(host, port);
NetworkStream networkStream = tcpClient.GetStream();
...
// Server Reply
if (networkStream.CanRead)
{
// Buffer to store the response bytes.
byte[] readBuffer = new byte[tcpClient.ReceiveBufferSize];
// String that will contain full server reply
StringBuilder fullServerReply = new StringBuilder();
int numberOfBytesRead = 0;
do
{
numberOfBytesRead = networkStream.Read(readBuffer, 0, readBuffer.Length);
fullServerReply.AppendFormat("{0}", Encoding.UTF8.GetString(readBuffer, 0, tcpClient.ReceiveBufferSize));
} while (networkStream.DataAvailable);
}
You're not using numberOfBytesRead. It is fascinating to me that every 2nd TCP question has this same issue as its answer.
Apart from that, you cannot split UTF-8 encoded string at arbitrary boundaries. Encoding.UTF8.GetString will return garbage. Use StreamReader.
The code is just horribly wrong. #usr already pinpointed two big mistakes.
Here is corrected code:
// Server Reply
if (networkStream.CanRead) {
// Buffer to store the response bytes.
byte[] readBuffer = new byte[tcpClient.ReceiveBufferSize];
string fullServerReply = null;
using (var writer = new MemoryStream()) {
while (networkStream.DataAvailable) {
int numberOfBytesRead = networkStream.Read(readBuffer, 0, readBuffer.Length);
if (numberOfBytesRead <= 0) {
break;
}
writer.Write(readBuffer, 0, numberOfBytesRead);
}
fullServerReply = Encoding.UTF8.GetString(writer.ToArray());
}
}

Transfer bitmap from C# server program over TcpClient to Java Socket gets corrupted

Server program C#
private TcpListener serverSocket;
..
init:
serverSocket = new TcpListener(ipAddress, port_number);
when new connection request found:
TcpClient clientSock = default(TcpClient);
clientSock = serverSocket.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
String FileName = requested binary data file name from client
Byte[] sendBytes = null;
if (File.Exists(pkgName))
{
//load file contents
sendBytes = File.ReadAllBytes(pkgName);
}
if (sendBytes != null)
{
networkStream.Write(sendBytes, 0, sendBytes.Length); //sendBytes.Length = 1001883;
networkStream.Flush();
}
...
Java Android code: client
InetAddress serverAddr = InetAddress.getByName(serverIp);
Log.d("SideloadManager", "C: Connecting...");
Socket socket = new Socket(serverAddr, serverPort);
InputStream inFromServer = socket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
FileOutputStream outStream = new FileOutputStream("...\recieved.bmp");
int size = 1001883; //same size from server
byte[] buf = new byte[size];
in.read(buf);
outStream.write(buf, 0, buf.length);
outStream.flush();
outStream.close();
received.bmp is of same size as on server 1001883 bytes. But its contents gets corrupted. After debugging i have seen that:
on C# program byte array is [ 149, 145, 10, .....]
on Java program byte array is: [ -105, -101, 10, .....] this is due to signed byte in java
What am i missing to receive correct bitmap?
SOLVED as below:
Replace:
int size = 1001883; //same size from server
byte[] buf = new byte[size];
in.read(buf);
outStream.write(buf, 0, buf.length);
with this:
int len=-1;
byte[] buf = new byte[1024];
while ((len = in.read(buf, 0, buf.length)) > 0) {
outStream.write(buf, 0, len);
}
solved the issue :)
The data is transferred correctly because 149 and -105 have the same binary representation as bytes. The more likely problem is that you're not reading all of the data that was sent in the java side.
The read method returns the number of bytes that have been read, and -1 when the end of the stream has been reached. You need a loop to read the entire file:
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
outStream.write(buf, 0, bytesRead);
}

Categories