How to read response code from TcpClient - c#

I just wonder how to read Response code from TCP client? The sample codes are below.
var tcpClient = new TcpClient();
tcpClient.Connect(this.Settings.MailServer, this.Settings.MailServerPort);
NetworkStream stream = tcpClient.GetStream();

Stream > byte > String
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(response);

You could use this:
byte[] message = new byte[512];
int bytesRead;
bytesRead = stream.Read(message, 0, message.Length);
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(encoder.GetString(message, 0, bytesRead));

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.

Too many bytes received on my server socket

I have a listening socket on my UWP device.
This the code for that:
List<byte> requestInBytes = new List<byte>();
using (IInputStream input = args.Socket.InputStream)
{
byte[] data = new byte[BufferSize];
IBuffer buffer = data.AsBuffer();
uint dataRead = BufferSize;
while (dataRead == BufferSize)
{
await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
requestInBytes.AddRange(data);
dataRead = buffer.Length;
}
}
var ct = requestInBytes.Count;
The count returned on that is:
630784
On my client Winform desktop I am sending the byte array as follows:
using (TcpClient clientSocket = new TcpClient())
{
await clientSocket.ConnectAsync(GeneralTags.RASPBERRY_PI_IP_ADDRESS, GeneralTags.RASPBERRY_PI_PORT);
using (NetworkStream serverStream = clientSocket.GetStream())
{
List<byte> requestInBytes = new List<byte>();
serverStream.Write(byteArray, 0, byteArray.Length);
serverStream.Flush();
}
}
The count of what I am sending is:
626840
Why are there more bytes received into my server?
The problem is that you add the entire buffer array data regardless of the actual number of received bytes.
Change the line
requestInBytes.AddRange(data)
to
requestInBytes.AddRange(data.Take(buffer.Length))

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

Socket Receive equivalent on NetworkStream/TcpClient

Using socket I can do so to get the bytes
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] buffer = new byte[1000000];
s.Receive(buffer, buffer.Length, SocketFlags.None);
//
FileStream fs = File.Create("1.jpg");
fs.Write(buffer, 0, buffer.Length);
fs.Close();
I use this code to receive a byte [] of an image that I'm sending.
I need to convert this code to use TcpClient / NetworkStream to receive the byte [] sent
enter code here
This Code should be equivalent to yours:
var buffer = new byte[100000];
using (TcpClient tcp = new TcpClient(AddressFamily.InterNetwork)
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
})
{
await tcp.ConnectAsync("host", 12345);
if (tcp.Connected)
{
using (var stream = tcp.GetStream())
{
await stream.ReadAsync(buffer, 0, buffer.Length);
}
}
}
using (var fs = File.Create("1.jpg"))
{
await fs.WriteAsync(buffer, 0, buffer.Length);
}

httpwebrespose does not receive pdf file?

A web application that receive and send a pdf file with signature. I send pdf file in httpwebrequest to the application. But not receive that pdf file with httpwebresponse ?
My code
byte[] pdfFile = File.ReadAllBytes("c:\\sample.pdf");
WebRequest request = WebRequest.Create("URL");
request.Credentials = new NetworkCredential("Username", "Password");
request.Proxy.Credentials = new NetworkCredential("Username", "Password");
request.Method = "POST";
request.ContentLength = pdfFile.Length;
request.ContentType = "application/pdf";
Stream stream = request.GetRequestStream();
stream.Write(pdfFile, 0, pdfFile.Length);
stream.Close();
WebResponse resp = request.GetResponse();
var buffer = new byte[4096];
MemoryStream memoryStream = new MemoryStream();
Stream responseStream =resp.GetResponseStream();
{
int count;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write
(buffer, 0, responseStream.Read(buffer, 0, buffer.Length));
} while (count != 0);
}
resp.Close();
byte[] memoryBuffer = memoryStream.ToArray();
System.IO.File.WriteAllBytes(#"c:\sample1.txt", memoryBuffer);
int s = memoryBuffer.Length;
BinaryWriter binaryWriter =
new BinaryWriter(File.Open(#"c:\sample2.txt", FileMode.Create));
binaryWriter.Write(memoryBuffer);
binaryWriter.Close();
//Read Fully is :
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
One problem you have is in your reading:
int count;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, responseStream.Read(buffer, 0, buffer.Length));
} while (count != 0);
You're reading the buffer twice each time through the loop. The bytes you read the first time are lost because you overwrite them. Your code should be:
int count;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);
} while (count != 0);
Also: I don't understand why you're writing the PDF to the request stream. Are you trying to send the PDF to a server and have it send the same file back?
What, exactly, are you trying to do here?

Categories