Getting junk values while converting network stream to string - c#

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);

Related

How to send image as an HTTP response using TcpClient

In my job I have server and clients (several devices) connected in to the same network.
Clients contacts with server using their web-browser.
Server is running a C# program that uses TcpListener to receive requests from browsers.
I'm trying to send an image through TcpClientto client device but this is the result:
I'v tried:
Read image file as String
Read image file as Byte[]
After some searches inside Chrome Developer console i found an error
net::ERR_CONTENT_LENGTH_MISMATCH.
i don't know why Content-Length: length-in-byte value isn't correct even through new FileInfo(Target).Length.
Code I use:
TcpListener Listener = new TcpListener(local_address, 9090);
Listener.Start();
TcpClient client = Listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
string target = HeaderKeys.GetValue("target"); /* image file in the request*/
string mime_type = MimeType.Extract(target); /* mime-type of the file */
byte[] content = File.ReadAllBytes(target);
StreamWriter writer = new StreamWriter(ns);
// response header
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write($"Content-Type: {mime_type}");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + content.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(content);
writer.Flush();
client.Close();
I'v tried
NetworkStream directly.
reading image file in MemoryStream and NetworkStream to write.
reading image file as byte[] and convert it to Base64.
The issue was because of StreamWriter
I've solved the issue using this code:
TcpClient client = Listener.AcceptTcpClient();
Stream s = client.GetStream();
byte[] file_content = File.ReadAllBytes(file);
StringBuilder header = new StringBuilder();
header.Append("HTTP/1.1 200 OK\r\n");
header.Append($"Content-Type: {mime_type}\r\n");
header.Append($"Content-Length: {file_content .Length}\r\n\n");
byte[] h = Encoding.ASCII.GetBytes(header.ToString());
s.Write(content, 0, content.Length);
s.Write(b, 0, b.Length);
s.Flush();
client.Close();

Receive Raw HEX by socket and convert to string

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);
}

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

Sending large file consuming a lot of memory in c#

I am sending very large file over TCP/IP network which is working as expected.
Just one concern that how to send it efficiently so that memory consumption should be optimized.
Below is the working code
Stream fileStream = File.OpenRead(tbFilename.Text);
byte[] fileBuffer = new byte[fileStream.Length];
fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
// Open a TCP/IP Connection and send the data
TcpClient clientSocket = new TcpClient(tbServer.Text,8080);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(fileBuffer,0,fileBuffer.GetLength(0));
networkStream.Close();
Firstly, Stream.Read will probably not read the whole file just a chunk, but you omit the return value, which is the number of read bytes.
Secondly, you should use a smaller buffer (eg. 4K) and use that to send the file.
const int BUFSIZE = 4096;
long transferred = 0L;
long length = fileStream.Length;
using (BinaryReader br = new BinaryReader(fileStream))
{
while (transferred < length)
{
int chunkSize = Math.Min(length - transferred, BUFSIZE);
byte[] buffer = br.ReadBytes(chunkSize);
networkStream.Write(buffer, 0, chunkSize);
transferred += chunkSize;
// here you can even report some progress to adjust a ProgressBar or something
}
}
You can use Stream.CopyTo() to copy data from a source stream into another.
The CopyTo() method uses a temporary buffer as suggested by taffer.
Do not forget to Flush() the network stream afterwards.
using (Stream fileStream = File.OpenRead(tbFilename.Text))
{
TcpClient clientSocket = new TcpClient(tbServer.Text, 8080);
NetworkStream networkStream = clientSocket.GetStream();
fileStream.CopyTo(networkStream);
networkStream.Flush();
networkStream.Close();
clientSocket.Close();
}

C# Networkstream reads nothing

Just trying to use Networkstream, and this is a simple code i wrote:
Client side:
TcpClient c = new TcpClient();
c.Connect("10.0.0.4", 10);
NetworkStream ns = c.GetStream();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("first");
byte[] buffer2 = System.Text.Encoding.UTF8.GetBytes("second");
MemoryStream stream = new MemoryStream();
stream.Write(buffer, 0, buffer.Length);
stream.Write(buffer2, 0, buffer2.Length);
stream.CopyTo(ns);
This is the server side:
TcpListener tl = new TcpListener(IPAddress.Any, 10);
tl.Start();
TcpClient c = tl.AcceptTcpClient();
NetworkStream ns = new NetworkStream(c.Client);
byte[] buff = new byte[5];
ns.Read(buff,0,buff.Length);
string result = System.Text.Encoding.UTF8.GetString(buff);
MessageBox.Show(result);
only when i close the entire application the MessageBox line is executed , and im always getting a blank messagebox! which mean result doesnt contain nothing...
Any help?
On the client stream is positioned at the very end of the stream. Therefore, CopyTo has nothing left to copy.
Use stream.Position = 0; before copying.
Also, you don't seem to be aware of the fact that socket reads (in fact any stream read) can return less bytes than were requested (at least one). Your reading code must account for that. TCP does not preserve message boundaries.

Categories