TCP/IP CLIENT RECEIVE MULTIPLE MESSAGE - c#

I need a help about my server. I have a program that sends a message over a socket with a TCP/IP connection and gets acknowledgment. My current problem is: I'm sending data to the machine I'm using for it to print. The machine confirms that it has received the data each time. But now it has to give feedback that it has printed the data after confirming that it has received the data. In the program I wrote, I cannot receive 2 messages in a row from the machine. What do I need to do to listen to multiple messages over Socket?
The code I use is below. Thanks for helps...
private void clientBaglanti(string ipAdres, int portNumarasi)
{
try
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = IPAddress.Parse(ipAdres); //ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumarasi);
soket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
catch (Exception rt)
{
MessageBox.Show(rt.Message);
}
string sonMesaj;
sonMesaj = gonderilenText.ToCharArray().Aggregate("", (sonuc, c) => sonuc += ((!string.IsNullOrEmpty(sonuc) && (sonuc.Length + 1) % 3 == 0) ? " " : "") + c.ToString());
byte[] gonderilenVeri = sonMesaj.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
byte b = checksumHesap(gonderilenVeri);
string txtChecksum = b.ToString("X2");
string toplamMesaj = sonMesaj + (" ") + txtChecksum;
byte[] gonderilenSonVeri = toplamMesaj.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
int byteGonderilen = soket.Send(gonderilenSonVeri);
string stringGidenVeri = BitConverter.ToString(gonderilenSonVeri);
lstVtMakineHaberlesme.Items.Add("Gönderilen: " + stringGidenVeri);
byte[] cevap = new byte[1024];
int ht = soket.Receive(cevap);
string stringGelenVeri = BitConverter.ToString(cevap, 0, ht);
lstVtMakineHaberlesme.Items.Add("Gelen: " + stringGelenVeri);

Related

C# UDP Server Client not receiving each others messages?

so for my UDP C# chat application, I have a server program which is intended to recieve a response by listening for the client to send it on Port 8001, when it recieves the acknolwedement from the client it is supposed to send a message back to the client. However, though the client and server both say they are listening for each other, the server always immediately reports that it sent the message to IP address 0.0.0.0, so they are not linking, below is the code to the client and server:
Server:
const int listenPort = 8001;
bool done = false;
UdpClient listener = new UdpClient(listenPort);
try
{
while (!done)
{
string text_to_send = satt.Text;
if (text_to_send.Length == 0)
{
done = true;
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
try
{
string IPAddress1 = "";
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList)
{
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
IPAddress1 = Convert.ToString(IP);
}
else
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string data_recieved;
byte[] recieve_byte_array;
try
{
while (!done)
{
Console.WriteLine("Looking for attack buddies " + groupEP);
recieve_byte_array = listener.Receive(ref groupEP);
Console.WriteLine("New buddy found at + " + groupEP.ToString());
data_recieved = Encoding.ASCII.GetString(recieve_byte_array, 0, recieve_byte_array.Length);
Console.WriteLine(data_recieved);
}
}
catch (Exception n)
{
Console.WriteLine("Attack information could not be sent. Please make sure your buddies are reachable" + n.ToString());
}
}
}
}
catch (Exception j)
{
Console.WriteLine("Please make sure all needed information is filled out");
}
Client:
const int listenPort = 8001;
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string data_recieved;
string searchcount_sent = searchcount.ToString();
byte[] send_byte_array;
byte[] recieve_byte_array;
try
{
while (!done)
{
string IPAddress1 = "";
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList)
{
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
IPAddress1 = Convert.ToString(IP);
}
}
string text_to_send = "Request to connect from: " + IPAddress1;
if (text_to_send.Length == 0)
{
done = true;
}
else
{
MessageBox.Show("Now listening on port 8001.");
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse(RecieveIP.Text);
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 8001);
Console.WriteLine("Now sending out packet to be acknolwedged by lead computer.");
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("Listening for the attack information on port " + listenPort);
recieve_byte_array = listener.Receive(ref groupEP);
data_recieved = Encoding.ASCII.GetString(recieve_byte_array, 0, recieve_byte_array.Length);
try
{
sending_socket.SendTo(send_buffer, sending_end_point);
}
catch (Exception send_exception)
{
Console.WriteLine("Exception {0}", send_exception);
}
MessageBox.Show("Listening for attack information.");
The two computers are finding each other via arp-a. So wondering why they would not be receiving each others message? Thanks.

UDP client not receiving data

I have a problem communicating with a UDP device
public IPEndPoint sendEndPoint;
public void senderUdpClient(byte message_Type, byte Command_Class, byte command_code,int argument1, int argument2)
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40963;
// Calcul CheckSum
// We know the message plus the checksum has length 12
var packedMessage2 = new byte[12];
var packedMessage_hex = new byte[12];
// We use the new Span feature
var span = new Span<byte>(packedMessage2);
// We can directly set the single bytes
span[0] = message_Type;
span[1] = Command_Class;
span[2] = command_code;
// The pack is <, so little endian. Note the use of Slice: first the position (3 or 7), then the length of the data (4 for int)
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(3, 4), argument1);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(7, 4), argument2);
// The checksum
// The sum is modulo 255, because it is a single byte.
// the unchecked is normally useless because it is standard in C#, but we write it to make it clear
var sum = unchecked((byte)packedMessage2.Take(11).Sum(x => x));
// We set the sum
span[11] = sum;
// Without checksum
Console.WriteLine(string.Concat(packedMessage2.Take(11).Select(x => $#"\x{x:x2}")));
// With checksum
Console.WriteLine(string.Concat(packedMessage2.Select(x => $#"\x{x:x2}")));
Console.WriteLine(string.Concat(packedMessage2.Take(1).Select(x => $#"\x{x:x2}")));
UdpClient senderClient = new UdpClient();
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), receivePort);
Thread.Sleep(5000);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = senderClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
senderClient.Close();
MessageBox.Show("Message Sent");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
Form1
ObjHundler.senderUdpClient(1, 1, 0x24, 0 , 0);
there I build my message and I send it via port 40960
and I got a response via port 40963
Wireshark
On wireshark I send the message and the equipment sends a response but the code crashes in this line
Byte[] receiveBytes = senderClient.Receive(ref RemoteIpEndPoint);
Without filling in the table and without displaying any error message
Is there something missing from my code?
what could be the problem
Netstat -a cmd pour l'ip que j'utilise pour l'envoie 192.168.2.20
[CMD Netstat -a]
The solution =
you must create a UDPClient for reading.
It worked for me
public void senderUdpClient()
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40963;
UdpClient senderClient = new UdpClient();
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(receivePort);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//string returnData = Encoding.ASCII.GetString(receiveBytes);
senderClient.Close();
MessageBox.Show("Message Sent");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}

Cannot connect to another computer over TCP

I am working on a project that transfers files over TCP. It is written in .NET 4.7. The program works while the client connects on the server that is on the same computer but when I send it to a friend and I try to connect it I get an error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Currently the program only sends some information about the file that will be copied and is nothing is encrypted as I cannot send even these information.
Here's the code for the server (Invoke is used because it is run on a separate thread):
private void Server_Start()
{
try
{
// Set port on 13000
int port = 13000;
//Get the ip adress for the server
String localIp;
using (var client = new WebClient())
{
// Try connecting to Google public DNS and get the local endpoint as IP
// If failed to connect set IP as local IP
if (CheckForInternetConnection())
{
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIp = endPoint.Address.ToString();
}
}
catch (Exception e)
{
localIp = "127.0.0.1";
}
}
else
{
localIp = "127.0.0.1";
}
}
IPAddress IP = IPAddress.Parse(localIp);
// Create listener and start listening
server = new TcpListener(IP, port);
server.Start();
// Buffer for data
Byte[] bytes = new byte[256];
String data = string.Empty;
this.Invoke((MethodInvoker)(() => Log.Items.Add("Server started on ip: " + IP.ToString())));
while (true)
{
// Accepting requests
TcpClient client = server.AcceptTcpClient();
// Get the stream object
NetworkStream stream = client.GetStream();
// Read length of file name
byte[] nameLength = new byte[4];
stream.Read(nameLength, 0, 4);
int nameSize = BitConverter.ToInt32(nameLength, 0);
// Read the name of file
byte[] name = new byte[nameSize];
stream.Read(name, 0, nameSize);
String fileName = Encoding.UTF8.GetString(name);
// Read size of file
byte[] fileSizeB = new byte[4];
stream.Read(fileSizeB, 0, 4);
int fileSize = BitConverter.ToInt32(fileSizeB, 0);
// Read start signal
byte[] startB = new byte[9+1];
stream.Read(startB, 0, 9);
String start = Encoding.UTF8.GetString(startB);
this.Invoke((MethodInvoker)(() => Log.Items.Add("Size of name: " + nameSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Name of file: " + fileName)));
this.Invoke((MethodInvoker)(() => Log.Items.Add("File size: " + fileSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Start signal: " + start)));
// Response to client
byte[] message = Encoding.UTF8.GetBytes("Testmessage");
stream.Write(message, 0, message.Length);
}
server.Stop();
Log.Items.Add("Server started on ip: " + IP.ToString());
}
catch (Exception e)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(e)));
}
}
And here is the code for the client:
private void button1_Click(object sender, EventArgs e)
{
IPAddress iP = IPAddress.Parse(ConnectIp.Text);
int port = 13000;
int buffersize = 1024;
TcpClient client = new TcpClient();
NetworkStream netStream;
// Try to connect to server
try
{
client.Connect(new IPEndPoint(iP, port));
}
catch(Exception ex)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(ex.Message)));
return;
}
netStream = client.GetStream();
String path = "D:\\testingEnv\\test1\\testing\\Matematika\\2017\\Školsko\\2017-SS-skolsko-B-1234-zad.pdf";
String Filename = Path.GetFileName(path);
// We wish to send some data in advance:
// File name, file size, number of packets, send start and send end
byte[] data = File.ReadAllBytes(path);
// First packet contains: name size, file name, file size and "sendStart" signal
byte[] nameSize = BitConverter.GetBytes(Encoding.UTF8.GetByteCount(Filename)); // Int
byte[] nameB = Encoding.UTF8.GetBytes(Filename);
byte[] fileSize = BitConverter.GetBytes(data.Length);
byte[] start = Encoding.UTF8.GetBytes("sendStart");
// Last packet constains: "sendEnd" signal to stop reading netStream
byte[] end = Encoding.UTF8.GetBytes("sendEnd");
// Creating the first package: nameSize, fileName, fileSize and start signal
byte[] FirstPackage = new byte[4 + nameB.Length + 4 + 9];
nameSize.CopyTo(FirstPackage, 0);
nameB.CopyTo(FirstPackage, 4);
fileSize.CopyTo(FirstPackage, 4 + nameB.Length);
start.CopyTo(FirstPackage, 4 + nameB.Length + 4);
// Send the first pckage
netStream.Write(FirstPackage, 0, FirstPackage.Length);
byte[] buffer = new byte[30];
// Read the response
netStream.Read(buffer, 0, 11);
netStream.Close();
client.Close();
}
A friend tried to port forward the port 13000 but it didn't work either. We even tried with the firewall being down but nothing. I searched on the internet but couldn't find any solutions to the problem.
One thing to note is that both functions are in the same application. I don't know if that is the cause of the problem.
Does anyone know how what is the problem here?
Thanks in advance
Have you tried to connect to your server with telnet ? "telnet localhost 13000" or from other computer with correct ip and address nbr ? Try that while debugging your server code. If telnet works, then client code has some problem..

Send broadcast with unknown port

Is it possible, to send a broadcast for searching a server application, if i don't know the port on which the server is running? Or do i have to check every port?
To send a simple broadcast, i found the following code at the internet:
Server
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.Write("Running server..." + Environment.NewLine);
server.Bind(new IPEndPoint(IPAddress.Any, 48000));
while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
server.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Server got '" + buffer[0] + "' from " + tempRemoteEP.ToString() + Environment.NewLine);
Console.Write("Sending '2' to " + tempRemoteEP.ToString() +
Environment.NewLine);
server.SendTo(new byte[] { 2 },
tempRemoteEP);
}
Client
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 48000);
//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//Send message to everyone
client.SendTo(new byte[] { 1 }, AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
string serverIp;
try
{
//Recieve from server. Don't wait more than 3000 milliseconds.
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
client.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Client got '" + buffer[0] + "' from " +
tempRemoteEP.ToString() + Environment.NewLine);
//Get server IP (ugly)
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
}
catch
{
//Timout. No server answered.
serverIp = "?";
}
Console.Write("ServerIp: " + serverIp + Environment.NewLine);
Console.ReadLine();
But I don't know, wehter my server use port 48000.
To send a broadcast:
var port = 123;
var udp = new UdpClient();
var data = new byte[] { 1, 2, 3 };
udp.Send(data, data.Length, new IPEndPoint(IPAddress.Any, port));
If you don't know the port, you have to try all ports, which I do not recommend, since you're spamming the network.
What are you trying to do?

TCP IP Server with acknowledgement and receive data again

I have developed TCP/IP Server in C# listening on port and a GPS device is sending the data to server.
Initially, the device sends the IMEI number to server and server acknowledges with 01. After receiving the acknowledgement by device, a new packet of data is sent to server.
I am able to get IMEI number by TCP Server and after sending acknowledgement, i am not able to receive new packet data from client. I am including my code below also. Please let me know where i am wrong.
I have tested using hercules tcp server tool and next data packet is receiving successfully but from my application it is not working.
try
{
IPAddress ipAdress = IPAddress.Parse(ConfigurationManager.AppSettings["Server"].ToString());
// You can use local IP as far as you use the
//same in client
// Initializes the Listener
TcpListener myList = new TcpListener(ipAdress, int.Parse(ConfigurationManager.AppSettings["Port"].ToString()));
for (; ; )
{ // Run forever, accepting and servicing connections
//Start Listeneting at the specified port
myList.Start();
Console.WriteLine("Server running - Port: 8000");
Console.WriteLine("Local end point:" + myList.LocalEndpoint);
Console.WriteLine("Waiting for connections...");
Socket socket = myList.AcceptSocket();
// When accepted
Console.WriteLine("Connection accepted from " + socket.RemoteEndPoint);
byte[] b = new byte[1000];
int k = socket.Receive(b);
Console.WriteLine("echoed {0} bytes.", k);
Console.WriteLine("Reading IMEI....");
string hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, b.Length));
File.WriteAllText(#"C:\ClientFiles\testIMEI", hexStr);
ASCIIEncoding asen = new ASCIIEncoding();
string response = "01";
Console.WriteLine("Ackowledgement Data - " + response);
//
int sentBytes = socket.Send(asen.GetBytes(response));
Console.WriteLine("Acknowledgement data sent!\n");
int count = 0;
while (socket.Poll(-1, SelectMode.SelectRead))
{
b = new byte[1000];
k = socket.Receive(b);
if (k > 0)
{
count++;
Console.WriteLine("Reading Client Data - Count - " + count.ToString() + " and lenght " + k.ToString());
hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, b.Length));
File.WriteAllText(#"C:\ClientFiles\testData" + count.ToString(), hexStr);
}
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
myList.Stop();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\ClientFiles\Error.txt", ex.Message + "****" + ex.InnerException);
}
I don't see any error in the program, except these comments:
// Don't use the b.Length in this command:
string hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, b.Length));
// use k instead, the numbers actually read, not the length of the buffer.
string hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, k));
while (socket.Poll(-1, SelectMode.SelectRead))
{
// b has been allocated, don't need this
// b = new byte[1000];
k = socket.Receive(b);
if (k > 0)
{
count++;
Console.WriteLine("Reading Client Data - Count - " + count.ToString() + " and lenght " + k.ToString();
// use k not Length
hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, k /*b.Length*/));
File.WriteAllText(#"C:\ClientFiles\testData" + count.ToString(), hexStr);
}
}
Do you know if the Poll command ever returns? May be it raises an error and you are missing that one. Check it out.

Categories

Resources