Socket is not receiving data from localhost - c#

I have c# code which is connecting to localhost ip address 127.0.0.1 and port no. 5939. Connection is happening perfectly but it is not receiving any data. I want it to receive data and save it to text file on my local machine.
Does it not receiving data because it is on the localhost and on the same machine or there is error in my code ..
Here is my code..
byte[] data = new byte[1024];
string input, stringData;
String ip = "127.0.0.1";
Int32 port = 5939;
string path = "D://ipdata.text";
if (File.Exists("D://ipsettings.txt"))
{
File.Delete("D://ipsettings.txt");
}
IPAddress ipad = IPAddress.Parse(ip);
IPEndPoint ipend = new IPEndPoint(ipad, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(ipend);
}
catch (Exception ex)
{
throw ex;
}
try
{
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
while (true)
{
input = "Client here";
sock.Send(Encoding.ASCII.GetBytes(input));
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
string df = "";
try
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
My program is not executing after this line..
int recv = sock.Receive(data);
Please help me to get out of this situation.
Thanks in advance.

You need to read the data until unless the Receive function gives you.
use while loop to determine whether data is available or not.
int recv=0;
byte[] data = new byte[1024];
StringBuilder sb= new StringBuilder();
while ((recv=sock.Receive(data)) > 0)
{
sb.Append(Encoding.ASCII.GetString(data, 0, recv));
}

Related

Discovering Lantronix XPort Pro and XPort using C# sockets

I am trying to find Lantronix XPort Pro devices on a network using C#. I am using some python code that I found on the Lantronix developer wiki as an example http://wiki.lantronix.com/developer/Lantronix_Discovery_Protocol.
The application I am writing is written in C# and I need to discover our units that have Lantronix devices installed. It seems that when I do the socket.RecieveFrom function call it just seems to hang the app.
Any ideas on what I am doing wrong. The python code from the link above detects the devices correctly. I should be able to duplicate this in C#.
Any help would be much appreciated.
private void FindLantronixXPort()
{
// This is the socket code that will broadcast from
// the local machine looking for responces from Lantronix
// XPort servers
// Create the array for our message chars
char[] chars = new char[4];
// Build the actual message
chars[0] = Convert.ToChar(0);
chars[1] = Convert.ToChar(0);
chars[2] = Convert.ToChar(0);
chars[3] = Convert.ToChar(0xf6);
// Convert the chars to a message string
string msg = new string(chars);
// Convert the setring to a byte array
byte[] data = Encoding.UTF8.GetBytes(msg);
// Get the local machines IP address
string Local_IP = GetIPAddress();
// Now create a broadcast UDP socket
Socket XmtSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
XmtSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(Local_IP), LantronixPort);
// Broadcast the packet
XmtSock.SendTo(data, 0, data.Length, SocketFlags.None, iep);
XmtSock.Close();
// Wait 500 mili seconds
int milliseconds = 500;
System.Threading.Thread.Sleep(milliseconds);
Socket RcvSock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
iep = new IPEndPoint(IPAddress.Any, LantronixPort);
RcvSock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive...");
byte[] data1 = new byte[120];
int recv = RcvSock.ReceiveFrom(data1, data1.Length, SocketFlags.None, ref ep);
string stringData = Encoding.ASCII.GetString(data1, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
RcvSock.Close();
}
Lantronix's wiki seems to be down at the moment, so I can't take a look at that for the moment. However, looking at your code it seems that you have to broadcast a UDP message, wait some time, and then check to see if anything has responded to that message.
However, it looks like you're creating a brand new socket for receiving the responses, but only after half a second. It's highly likely that any X-port that is going to respond will already have done so long before then (networks are fast, X-ports aren't very sluggish, etc). So I reckon the responses are hitting your OS'es network stack, which saying "well I dunno where that's supposed to go", and only after half a second are you creating a socket suitable for receiving the responses that the OS'es network stack has already discarded as unknown junk.
So move things around a bit is what I suggest. Set up the receiving socket, binding and endpoint before you transmit the broadcast message, so that it's ready there waiting for responses. See if that helps.
#WJD Your code for preparing byte array did not create content expected by XPort. It is why it did not replyed and hang on RecieveFrom().
I followed the link you gave for python example and created version in C#.
class Program
{
static void Main(string[] args)
{
Socket socket;
int GroupPort = 30718;
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
var localEP = new IPEndPoint(IPAddress.Parse("10.0.2.14"), GroupPort); // <-- your local IP address
socket.Bind(localEP);
socket.ReceiveTimeout = 200;
}
catch (TimeoutException e)
{
Console.WriteLine("Failed to create socket. " + e.Message);
return;
}
var remoteEP = new IPEndPoint(IPAddress.Broadcast, GroupPort);
try
{
byte[] messageBytes;
messageBytes = new byte[0];
messageBytes = AddByteToArray(messageBytes, 0xf6);
messageBytes = AddByteToArray(messageBytes, 0);
messageBytes = AddByteToArray(messageBytes, 0);
messageBytes = AddByteToArray(messageBytes, 0);
socket.SendTo(messageBytes, remoteEP);
}
catch (Exception e)
{
Console.WriteLine("Failed to send message. " + e.Message);
return;
}
var recvEp = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
var recvBytes = new byte[1024];
var receivedCount = socket.ReceiveFrom(recvBytes, ref recvEp);
var receivedArray = recvBytes.Take(receivedCount).ToArray();
var receivedArrayAsHexString = string.Join("", receivedArray.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));
string returnData = Encoding.ASCII.GetString(receivedArray);
Console.WriteLine($"Broadcast Respond from client {recvEp.ToString()} returned: {receivedArrayAsHexString}");
}
catch (Exception e)
{
socket.Close();
break;
}
}
Console.ReadLine();
}
public static byte[] AddByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
}

C# Socket does not send complete data

I am trying to create a client/server application where a server sends commands to clients and clients send result back. The clients send data like this:
5|Hello
5 is the length of the string which is sent because then the server knows howmany characters it should receive before it should do something with that data. I tried to do that with this code:
private static void ReceiveCallback(IAsyncResult AR)
{
try
{
while (!Encoding.ASCII.GetString(_buffer).Contains("|"))
{
}
string[] a = Encoding.ASCII.GetString(_buffer).Split('|');
while (Encoding.ASCII.GetString(_buffer).Length < (Int32.Parse(a[0]) + a[0].Length + 1))
{
}
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string text = Encoding.ASCII.GetString(dataBuf);
if (!text.Contains("GET") && !text.Contains("HTTP") && text != null)
{
Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + ":" + text);
}
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
catch
{
}
}
but this still does not give me the correct result. Also the CPU goes very high.
Picture of the result:
Can someone explain me why this happens? Thanks!
try to replace Encoding.ASCIIto Encoding.UTF8.
It can fix you issue.
Do note that you must to use the same encoding on both sides (sending and receiving data).
I hope it helps you.
have you tried using TcpClient? it can be way easier and gives you more control.
something like;
//make connection
NetworkStream stream = null;
socket = new TcpClient();
socket.Connect("192.168.12.12", 15879);
if (socket.Connected) {
stream = socket.GetStream();
}
//and than wait for tcp packets.
connectionThread = new Thread(ListenServer);
connectionThread.Start();
private void ListenToServer() {
Byte[] data = new Byte[1024];
String message = String.Empty;
Int32 dataLength = 0;
while (socket.Connected) {
try {
while (stream.DataAvailable) {
dataLength = stream.Read(data, 0, data.Length);
message = System.Text.Encoding.UTF8.GetString(data, 0, dataLength);
//do what ever you need here
Thread.Sleep(1);
}
} catch (Exception ex) {
}
Thread.Sleep(100);
}
moreover %1 cpu load!

C# send custom socket string

I have this code:
public static List<Socket> samp = new List<Socket>();
IPHostEntry host = null;
Socket sock;
host = Dns.GetHostEntry(sending ip..);
foreach (IPAddress address in host.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 7777);
sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipe);
if (sock.Connected)
{
samp.Add(sock);
}
}
This code work's okay. It send's my ip. How it looks in console:
How can I send custom string? For example i'm tried this code:
if (sock.Connected)
{
byte[] msg = Encoding.UTF8.GetBytes("This is a test");
byte[] bytes = new byte[256];
int i = sock.Send(msg);
MessageBox.Show(string.Format("Sent {0} bytes.", i));
samp.Add(sock);
}
It shows message: Sent 14 bytes. But in the console nothing prints.. How can I send this text to console? I'm also tried this:
sock.Send(Encoding.UTF8.GetBytes("This is a test"));
And this not prints :(
Thanks in advance !

Receiving null byte array from simulator

This is my code for a client to receive data from a server which is the simulator. While debugging the code, I received null values in this array, called receivedBytes:
// define buffer
byte[] receivedBytes = new byte[2048];
// define endpoint
IPHostEntry ipHost = Dns.Resolve("192.168.1.55");
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1001);
// connect
Console.WriteLine("Starting: Creating Socket object");
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Successfully connected to {0}", sender.RemoteEndPoint);
// get user input
Console.WriteLine("Enter Client Message :");
string sendingMessage = Console.ReadLine();
// send
Console.WriteLine("Creating message:{0}", sendingMessage);
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
sender.Send(forwardMessage);
// receive
int totalBytesReceived = sender.Receive(receivedBytes);
Console.WriteLine("Message provided from server: {0}", Encoding.Unicode.GetString(receivedBytes, 0, totalBytesReceived));
// close
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
What am I doing wrong here?
Actually the conversion code is wrong.
string sendingMessage = "Hello, World";
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
string receivedMessage = Encoding.Unicode.GetString(forwardMessage, 0,forwardMessage.Length);
After that receivedMessage will be broken.
What it does? It gets default encoding to GetBytes and than uses UTF-16 encoding to get string. You should use Encoding.Default.GetBytes and Encoding.Default.GetString.

UDP client in C#

Am trying to make a simple UDP application using C sharp,nothing sophisticated,connect,send some text,and receive it! but it keeps throwing this exception!
"An existing connection was forcibly closed by the remote host"!
The code :
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tmpRemote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
Console.WriteLine("Stopping client");
server.Close();
thanks =)
You should tell the system that you are listening for UDP packets on port 9050 before you call Receive.
Add server.Bind(ipep); after Socket server = new Socket(...);
Have you tried checking that the IP address is valid and the port is not being used for something else?
Windows:
Start > Run > "cmd" > "ipconfig".
Try turning off your firewall software.
If you do not know the IP of the answering server, you better do:
recv = server.Receive(data);
Here is my suggetion to your code. You can use a do-while loop using a condition (in my example it is an infinite loop):
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.ReceiveTimeout = 10000; //1second timeout
int rslt = server.SendTo(data, data.Length, SocketFlags.None, ipep);
data = new byte[1024];
int recv = 0;
do
{
try
{
Console.WriteLine("Start time: " + DateTime.Now.ToString());
recv = server.Receive(data); //the code will be stoped hier untill the time out is passed
}
catch { }
} while (true); //carefoul! infinite loop!
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
Console.WriteLine("Stopping client");
server.Close();

Categories