Send and receive byte[] in server-client TCP application - c#

I need to send and receive bytes in from my client to server over NetworkStream. I know how to communicate with strings, but now I need to send and receive bytes.
For example, something like that:
static byte[] Receive(NetworkStream netstr)
{
try
{
byte[] recv = new Byte[256];
int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
return recv;
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
return null;
}
}
static void Send(NetworkStream netstr, byte[] message)
{
try
{
netstr.Write(message, 0, message.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
}
}
Server:
private void prejmi_click(object sender, EventArgs e)
{
const string IP = "127.0.0.1";
const ushort PORT = 54321;
TcpListener listener = new TcpListener(IPAddress.Parse(IP), PORT);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte[] data = Receive(ns)
}
Client:
private void poslji_Click(object sender, EventArgs e)
{
const string IP = "127.0.0.1";
const ushort PORT = 54321;
TcpClient client = new TcpClient();
client.Connect(IP, PORT);
string test="hello";
byte[] mybyte=Encoding.UTF8.GetBytes(test);
Send(ns,mybyte);
}
But that is not the propper way to do this, because byte[] data on server side will always have length of 256.

Thanks, Jon!
static byte[] Receive(NetworkStream netstr)
{
try
{
// Buffer to store the response bytes.
byte[] recv = new Byte[256];
// Read the first batch of the TcpServer response bytes.
int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
byte[] a = new byte[bytes];
for(int i = 0; i < bytes; i++)
{
a[i] = recv[i];
}
return a;
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
return null;
}
}
static void Send(NetworkStream netstr, byte[] message)
{
try
{
//byte[] send = Encoding.UTF8.GetBytes(message.ToCharArray(), 0, message.Length);
netstr.Write(message, 0, message.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
}
}

Related

How to communicate with the alarm Sur-Gard System 1

I need to develop a software that catch all alarm alerts from a Sur-Gard System 1.
For now I created this tcp listener en c# and works fine using my phone as a client but it does not stablish communication with the Sur-Gard, I pingued to the sur-gard IP and there is communication between them, and I'm sure that the port it's correct.
What I'm doing wrong?
static void Main(string[] args)
{
Reconect:
System.Net.Sockets.TcpListener server = null;
try
{
Int32 port = 1025;
server = new System.Net.Sockets.TcpListener(IPAddress.Any, port);
server.Start();
while (true)
{
Console.WriteLine($#"Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
goto Reconect;
}
private static void ThreadProc(object obj)
{
var client = (TcpClient)obj;
Console.WriteLine("Connected!");
Byte[] bytes = new Byte[1024];
String cadena_obtenida = null;
cadena_obtenida = null;
NetworkStream stream = client.GetStream();
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
cadena_obtenida = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Alerta recibida: {0}", cadena_obtenida);
byte[] respuesta = System.Text.Encoding.ASCII.GetBytes("El servidor ha recibido: " + cadena_obtenida + Environment.NewLine);
stream.Write(respuesta, 0, respuesta.Length);
stream.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
client.Close();
}

TCPlistener server-client and client-server ( send message to client from server)

All i want to do is send message to client from server. I try a lot of tutorial etc. but still can't send message from server to client.
Send from client to server is simple and have it in code. When client Send "HI" to server i want to respond Hi to client. But dunno what should i add to my code. Can someone help me with that? Please don't do it like duplicate i know there is a lot of similar topic but can't find solution.
Server code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener server = new TcpListener(ip, Convert.ToInt32(8555));
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
};
while (true)
{
client = server.AcceptTcpClient();
byte[] receivetBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivetBuffer, 0, receivetBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach(byte b in receivetBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
////Resive message :
if (msg.ToString() =="HI")
{
///#EDIT 1
///// HERE Is SENDING MESSAGE TO CLIENT//////////
int byteCount = Encoding.ASCII.GetByteCount("You said HI" + 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("You said HI" + ";");
stream.Write(sendData, 0, sendData.Length);
}
}
Client code:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string serverIP = "localhost";
int port = Convert.ToInt32(8555);
TcpClient client = new TcpClient(serverIP, port);
int byteCount = Encoding.ASCII.GetByteCount("HI"+ 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("HI" + ";");
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
///////////////////////////////HERE I WANT A read message from server/
/////////////////////////////////////////////////////////////////////
stream.Close();
client.Close();
}
catch(Exception ex)
{
ex.ToString();
}
}
Try this Here is my version of client and server ,feel free to ask if any reference problem ,the client wait for server to (online) then if server is online connect with it.
Method to Connect with Server
private void Connectwithserver(ref TcpClient client)
{
try
{
//this is server ip and server listen port
server = new TcpClient("192.168.100.7", 8080);
}
catch (SocketException ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
RunBoTClient();
}
}
byte[] data = new byte[1024];
string stringData;
TcpClient client;
private void RunClient()
{
NetworkStream ns;
Connectwithserver(ref client);
while (true)
{
ns = client.GetStream();
//old
// ns.ReadTimeout = 50000;
//old
ns.ReadTimeout = 50000;
ns.WriteTimeout = 50000;
int recv = default(int);
try
{
recv = ns.Read(data, 0, data.Length);
}
catch (Exception ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
//try to reconnect if server not respond
RunClient();
}
//READ SERVER RESPONSE/MESSAGE
stringData = Encoding.ASCII.GetString(data, 0, recv);
}
}
Server
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//IF YOU WANT TO WRITE BACK TO CLIENT USE
string yourmessage = console.ReadLine();
Byte[] sendBytes = Encoding.ASCII.GetBytes(yourmessage);
//---write back the text to the client---
Console.WriteLine("Sending back : " + yourmessage );
nwStream.Write(sendBytes, 0, sendBytes.Length);
client.Close();
}
listener.Stop();

Specified argument was out of the range of valid values. Parameter name: size

I'm extremely new to any type of networking with programming. When trying to create a simple socket server program I get the following error:
Specified argument was out of the range of valid values.
Parameter name: size
Here is my code for the server:
class Program
{
private static IPAddress localServerIP = IPAddress.Parse("10.114.130.223");
private static TcpListener serverSocket;
private static TcpClient clientSocket;
private static int requestCount = 0;
static void Main(string[] args)
{
serverSocket = new TcpListener(localServerIP, 8888);
clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started\n");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while (true)
{
try
{
requestCount++;
NetworkStream networkStream = clientSocket.GetStream();
byte[] dataBuffer = new byte[10025];
networkStream.Read(dataBuffer, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(dataBuffer);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
And this is my client
public partial class Form1 : Form
{
private TcpClient clientSocket;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket = new TcpClient();
try
{
clientSocket.Connect(IPAddress.Parse("10.114.130.223"), 8888);
}
catch
{
textBox1.AppendText(" >> Server unavailable\n");
}
statusLabel.Text = "Client Socket Program - Server Connected";
}
private void sendBtn_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returnData = Encoding.ASCII.GetString(inStream);
msg(returnData);
textBox2.Text = "";
textBox2.Focus();
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
}
Any help or guidance or explanation would greatly be appreciated.
It's either from
networkStream.Read(dataBuffer, 0, (int)clientSocket.ReceiveBufferSize);
or from
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Read the docs for NetworkStream.Read Exceptions and for substring exceptions.

How to manage the messages from the client to server

I have some clients that connect to the server at the same time, and each of them send to server a registration message.
So, the messages collide with previous messages when they come to the server.
How can I manage the communications without collision between the messages?
I use asynchronous tcp socket in C#.
Here the server:
class ServerSocket
{
//The ClientInfo structure holds the required information about every
//client connected to the server
struct ClientInfo
{
public Socket socket; //Socket of the client
public string strName; //Name by which the user logged into the chat room
}
//The collection of all clients logged into the room (an array of type ClientInfo)
ArrayList clientList;
//The main socket on which the server listens to the clients
Socket serverSocket;
byte[] byteData = new byte[5000];
const int NUM_CLIENT = 12;
public ServerSocket()
{
clientList = new ArrayList();
}
public void LoadServer()
{
try
{
//We are using TCP sockets
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Assign the any IP of the machine and listen on port number 1000
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);
//Bind and listen on the given address
serverSocket.Bind(ipEndPoint);
serverSocket.Listen(NUM_CLIENT);
//Accept the incoming clients
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
Console.WriteLine("###################### S E R V E R ######################");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void OnAccept(IAsyncResult ar)
{
try
{
Socket clientSocket = serverSocket.EndAccept(ar);
//Start listening for more clients
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
//Once the client connects then start receiving the commands from her
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void OnReceive(IAsyncResult ar)
{
string msgReceived = "";
try
{
Socket clientSocket = (Socket)ar.AsyncState;
clientSocket.EndReceive(ar);
msgReceived = GetString(byteData);
string strTemp = "";
for (int i = 0; i < msgReceived.IndexOf("<END>"); i++)
{
strTemp += msgReceived[i];
}
msgReceived = strTemp;
XmlBaseClientMsg xmlBaseClientMsg = new XmlBaseClientMsg();
BaseClientMsg baseClientMsgReceived = new BaseClientMsg();
baseClientMsgReceived = xmlBaseClientMsg.DeserializeFromString(msgReceived);
switch (baseClientMsgReceived.m_messageType)
{
case ClientMsgType.AI_REGISTRATION:
//When a user logs in to the server then we add him to our list of clients
ClientInfo AIClientInfo = new ClientInfo();
AIClientInfo.socket = clientSocket; // save the socket
AIClientInfo.strName = baseClientMsgReceived.m_sSenderID; // save the name of sender client
clientList.Add(AIClientInfo);
Console.WriteLine("The client: " + AIClientInfo.strName + " registered");
break;
case ClientMsgType.ENTITY_REGISTRATION:
//When a user logs in to the server then we add him to our list of clients
ClientInfo EntityClientInfo = new ClientInfo();
EntityClientInfo.socket = clientSocket; // save the socket
EntityClientInfo.strName = baseClientMsgReceived.m_sSenderID; // save the name of sender client
clientList.Add(EntityClientInfo);
Console.WriteLine("The client: " + EntityClientInfo.strName + " registered");
break;
#region
//case Command.Logout:
// //When a user wants to log out of the server then we search for her
// //in the list of clients and close the corresponding connection
// int nIndex = 0;
// foreach (ClientInfo client in clientList)
// {
// if (client.socket == clientSocket)
// {
// clientList.RemoveAt(nIndex);
// break;
// }
// ++nIndex;
// }
// clientSocket.Close();
// break;
#endregion
}
if (baseClientMsgReceived.m_messageType != ClientMsgType.AI_REGISTRATION)
{
Console.WriteLine("Type message: " + baseClientMsgReceived.m_messageType + " To: " +
baseClientMsgReceived.m_sReceiverID + " From: " + baseClientMsgReceived.m_sSenderID);
foreach (ClientInfo clientInfo in clientList)
{
if (clientInfo.strName == baseClientMsgReceived.m_sReceiverID)
{
byte[] message;
message = GetBytes(msgReceived);
// Send the message to reciever client
clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(OnSend), clientInfo.socket);
Console.WriteLine("Msg No : " + baseClientMsgReceived.m_nMessageID + " Type: " + baseClientMsgReceived.m_messageType + " ==> has been sent");
break;
}
}
}
////If the user disconnects so no need to listen to him
// if (baseClientMsgReceived.m_messageType != ClientMsgType.Logout)
//{
//Start listening to the message send by the user
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
//}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void OnSend(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndSend(ar);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
}
class Program
{
public static int Main( String[] args )
{
ServerSocket serverSocket = new ServerSocket();
serverSocket.LoadServer();
while(true)
{
Console.ReadLine();
}
}
}
}

Send Hex from php to device using socket_sendto

I have spent days trying to figure this out. I have a GPS tracker device that communicates using UDP protocol.
And I have a hex string I need to send to this tracker:
"0d0a2a4b5700440002000000000000002a4b572c4e5230394230353330342c3030372c3034333133392c3023000000000000000000000000000000000000000000000d0a"
If I send this string using c#, the device replies back. C# Code:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
// Send Message to tracker
public static void send(string ip, string port, string msg)
{
Byte[] sendBytes = StringToByteArray(msg);
try
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
UDPreceiver.Send(sendBytes, sendBytes.Length, ipEndPoint);
Program.form1.addlog("Sent: " + ByteArrayToString(sendBytes) + " - to " + ip + " on port: " + port);
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "error");
}
}
Now If I try to send the same hex string from PHP. The device does not respond, here's the php code:
// Function send
function send($ip,$port,$message){
$socket_bytes = false;
try {
// Prepare message
$strlen = strlen($message);
$message = hex2bin(strtoupper($message));
// Send Packet
if(!($this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))){
die('msg,could not create socket');
}
$socket_bytes = socket_sendto($this->socket, $message, $strlen, 0, $ip, $port);
socket_close($this->socket);
}catch(Exception $e){
return false;
}
return $socket_bytes;
}
I have exhausted my self trying to figure out how to send this. Please any help would be very appreciated.
I'm not sure but
strlen($message) != strlen(hex2bin(strtoupper($message)));
$message = 'ABCD';
echo strlen($message); //==4
echo "\n";
echo strlen(hex2bin(strtoupper($message))); //==2

Categories