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);
}
Related
I'm a newbie and I'm having a small Socket programming exercise.
User input an array from Client and Server calculator it ( + ,* ) and send to client total
This my code but it doesn' run correctly.
My code
Server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace sv
{
class Program
{
static void Main(string[] args)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2016);
Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
server.Bind(iep);
server.Listen(10);
Console.WriteLine("waiting...");
Socket client = server.Accept();
Console.WriteLine("Accept {0}", client.RemoteEndPoint.ToString());
string s = "Welcome";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(s);
client.Send(data, data.Length, SocketFlags.None);
while (true)
{
data = new byte[1024];
int recv = client.Receive(data);
string c = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Client: {0}", c);
}
byte[] gdata = new byte[1024];
byte[] total = new byte[1024];
string array;
while (true)
{
int recv = client.Receive(gdata);
array = Encoding.ASCII.GetString(gdata, 0, recv);
Console.WriteLine("Client: {0}", array);
//SUM
int sum = 0;
string[] arrListStr = array.Split(new char[] { ' ' });
for (int i = 0; i < arrListStr.Length; i++)
{
sum += Int32.Parse(arrListStr[i]);
}
array = sum.ToString();
total = Encoding.ASCII.GetBytes(array);
client.Send(total, total.Length, SocketFlags.None);
}
Console.ReadKey();
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace cl
{
class Program
{
static void Main(string[] args)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2016);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(iep);
byte[] data = new byte[1024];
int recv = client.Receive(data);
string s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("From Server : {0}", s);
string input;
while (true)
{
input = Console.ReadLine();
data = new byte[1024];
data = Encoding.ASCII.GetBytes(input);
client.Send(data, data.Length, SocketFlags.None);
}
data = new byte[1024];
recv = client.Receive(data);
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("From Server : {0}, s");
Console.ReadKey();
}
}
}
Pls help me fix it. Thanks <3
change your code like below, it will give you the sum
pass values from client as comma separated like 12,13
server
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2016);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(iep);
server.Listen(10);
Console.WriteLine("waiting...");
Socket client = server.Accept();
Console.WriteLine("Accept {0}", client.RemoteEndPoint.ToString());
string s = "Welcome";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(s);
client.Send(data, data.Length, SocketFlags.None);
byte[] gdata = new byte[1024];
byte[] total = new byte[1024];
string array;
while (true)
{
int recv = client.Receive(gdata);
array = Encoding.ASCII.GetString(gdata, 0, recv);
Console.WriteLine("Client: {0}", array);
//SUM
int sum = 0;
string[] arrListStr = array.Split(',');
for (int i = 0; i < arrListStr.Length; i++)
{
sum += Int32.Parse(arrListStr[i]);
}
array = sum.ToString();
total = Encoding.ASCII.GetBytes(array);
client.Send(total, total.Length, SocketFlags.None);
}
client
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2016);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(iep);
byte[] data = new byte[1024];
int recv = client.Receive(data);
string s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("From Server : {0}", s);
string input;
while (true)
{
input = Console.ReadLine();
data = new byte[1024];
data = Encoding.ASCII.GetBytes(input);
client.Send(data, data.Length, SocketFlags.None);
// data = new byte[1024];
recv = client.Receive(data);
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("From Server : {0}", s);
Console.ReadKey();
}
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))
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));
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);
}
I am trying to retrieve the byte that transferred by the server that has been programmed in c# as follow:
static void Main(String[] args){
Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress IP = IPAddress.Parse("10.0.0.92");
IPEndPoint IPE = new IPEndPoint(IP, 4321);
sListen.Bind(IPE);
Console.WriteLine("Service is listening ...");
sListen.Listen(2);
while (true){
Socket clientSocket;
try{
clientSocket = sListen.Accept();
}
catch{
throw;
}
byte[] buffer = ReadImageFile("path to image");
clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
Console.WriteLine("Send success!");
}
}
private static byte[] ReadImageFile(String img){
FileInfo fileinfo = new FileInfo(img);
byte[] buf = new byte[fileinfo.Length];
FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);
fs.Read(buf, 0, buf.Length);
fs.Close();
//fileInfo.Delete ();
GC.ReRegisterForFinalize(fileinfo);
GC.ReRegisterForFinalize(fs);
return buf;
}
Above codes works fine when I write a client in the c# and run it in the pc. However I want to retrieve the bytes transferred by the server in the android device.
The android connected to the server successfully but it will not finish its job, basically it will not pass the ‘while loop in the bellow code’. I think there is something wrong with the byte length because it’s never get to ‘-1’.
Android java code (Client):
Socket socket = new Socket("ip", 4321);
InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024];
int read = is.read(buffer);
while(read != -1){
read = is.read(buffer);
}
is.close();
socket.close();
I do appreciate any help in advance,
Thanks,
The client read() method will never return -1 until the server closes the connection. You're not doing that so it never happens.
I don't get the point of your Java code. The read(byte[]) method you are using writes 1024 bytes (or less) in the buffer again and again. You are overwriting your previous buffer content. You probably would like to write the downloaded data to somewhere, like an OutputStream. Example:
Socket socket = new Socket("ip", 4321);
InputStream is = socket.getInputStream();
OutputStream os = ...; // Where to save data, for example, new ByteArrayOutputStream();
copyStreams(is, os);
is.close();
socket.close();
public static void copyStreams(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[1024];
int numBytesRead;
for (;;) {
bytesRead = is.read(buffer);
if (bytesRead <= 0)
break;
os.write(buffer, 0, bytesRead);
}
}