c# client-server using UDP Connection - c#

I am trying to make client Server appilcation in c#. On the Client side i write hello message to Server and Server receives the message.
once the Server receive the message, it should send back client a messsage indicating that message has been received. Basically an acknowledment.
My Problem is that Client doesn´t receive the message form Server.
On down is my code for both Client and Server.
Client part:
string x = "192.168.1.4";
IPAddress add = IPAddress.Parse(x);
IPEndPoint point = new IPEndPoint(add, 2789);
using (UdpClient client = new UdpClient())
{
byte[] data = Encoding.UTF8.GetBytes("Hello from client");
client.Send(data, data.Length, point);
string serverResponse = Encoding.UTF8.GetString(client.Receive(ref point));
Console.WriteLine("Messahe received from server:"+ serverResponse);
}
Server part:
try
{
while (true)
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
Console.WriteLine("Client address is:" + groupEP.Address.ToString());
Console.WriteLine("Client port is:" + groupEP.Port.ToString());
byte[]data = new byte[1024];
UdpClient listener = new UdpClient(2789);
Console.WriteLine("Waiting for client");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received Data:"+ Encoding.ASCII.GetString(bytes, 0, bytes.Length));
//sending acknoledgment
string welcome = "Hello how are you from server?";
byte[]d1 = Encoding.ASCII.GetBytes(welcome);
listener.Send(d1, d1.Length, groupEP);
Console.WriteLine("Message sent to client back as acknowledgment");
}
}

I compiled your code and it work so your issue is an "outside" problem such as :
A firewall is blocking something (either the connection or the server binding).
Because the ip in your sample is a lan ip it is probably the built-in firewall from Windows (or a third-party firewall).
Try to disable your firewall, here is how to disable the built-in firewall of Windows.
You test the client on a different computer than the server and use the wrong ip.
If you do test on the same machine you may use the special ip 127.0.0.1 (aka the DNS localhost). 127.0.0.1 always refer to the computer that is running the code. Using this special ip may avoid you trouble in future if your local ip does changes.
And by the way, in your server code you should reuse the "listener" field for each interation of while() such as in
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 2789);
Console.WriteLine("Client address is:" + groupEP.Address.ToString());
Console.WriteLine("Client port is:" + groupEP.Port.ToString());
byte[] data = new byte[1024];
UdpClient listener = new UdpClient(2789);
while (true)
{
Console.WriteLine("Waiting for client");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received Data:" + Encoding.ASCII.GetString(bytes, 0, bytes.Length));
//sending acknoledgment
string welcome = "Hello how are you from server?";
byte[] d1 = Encoding.ASCII.GetBytes(welcome);
listener.Send(d1, d1.Length, groupEP);
Console.WriteLine("Message sent to client back as acknowledgment");
}

Related

Tcp connection fails on LAN

I am trying to send a message from my laptop to my desktop over the LAN.
I have written a Tcp server that listens for a connection on a port, and a client that tries to connect to it and send a simple string as a message.
Server:
void Listen()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
while (true)
{
Debug.Log($"listening to {listener.LocalEndpoint}...");
var socket = listener.AcceptSocket();
Debug.Log("connected!");
var bytes = new byte[100];
int k = socket.Receive(bytes);
var data = Encoding.ASCII.GetString(bytes, 0, k);
Debug.Log(data);
socket.Send(new byte[] {1});
Debug.Log("responded");
socket.Close();
Debug.Log("closed connection");
}
}
Client:
public void Send()
{
client = new TcpClient();
Debug.Log("connecting...");
client.Connect("192.168.0.12", port);
Debug.Log("connected!");
var data = Encoding.ASCII.GetBytes("Hello!");
var stream = client.GetStream();
Debug.Log("sending data");
stream.Write(data, 0, data.Length);
Debug.Log("data sent! waiting for response...");
var reply = new byte[100];
stream.Read(reply,0,100);
Debug.Log("received response");
client.Close();
}
They communicate correctly when they are both on the same machine, but the client never connects to the server when I am running it on a different machine.
I have a rule in my firewall that allows an incoming connection through the port I have specified.
I have tried it with both computer's firewalls off and the connection still doesn't go through.
Any help would be greatly appreciated.

Connection Refused with TCP socket Error # 10061

I'm creating a small chat (1-1) application to learn network programming and when creating the socket using TCP protocol, the Socket.Connect() always return error 10061.
However, if I make the socket UDP, I don't see the issue.
Here is my code:
myEndPoint = new IPEndPoint(IPAddress.Parse(_txtMyIPAdress.Text), int.Parse(_txtMyPort.Text));
TargetSideEndPoint = new IPEndPoint(IPAddress.Parse(_txtTargetIPAddress.Text), int.Parse(_txtTargetPort.Text));
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.Bind(myEndPoint);
mySocket.Connect(TargetSideEndPoint);
byte[] receivedBuffer = new byte[MAX_BUFFER_SIZE = 1024];
ReceivePackets(mySocket, receivedBuffer);//My function
Can any one help me?
Update:
I'm not using Listen() the issue is when I call Connect()
I already tried multiple ports with the same issue and I'm currently testing on 1 PC by opening 2 instances from my application and using 2 different ports while firewall is off.
Thanks,
For TCP, which is a connection oriented protocol, you would need a server and a client.
The server must listen for incoming connections and the client should initiate the connection. Then, the client will be able to communicate with the server and exchange data.
Here is a simple working example:
void Main()
{
Console.WriteLine("Starting listener thread");
Thread serverThread = new Thread(ListenerThreadProc);
serverThread.Start();
Console.WriteLine("Waiting 500 milliseconds to allow listener to start");
Thread.Sleep(500);
Console.WriteLine("Client: Connecting to server");
TcpClient client = new TcpClient();
client.Connect(IPAddress.Loopback, 12345);
Console.WriteLine("Client: Connected to server");
byte[] buffer = new byte[5];
Console.WriteLine("Client: Receiving data");
using (NetworkStream clientStream = client.GetStream())
clientStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Client: Received data: " + buffer.Aggregate("", (s, b) => s += " " + b.ToString()));
}
void ListenerThreadProc()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server: Listener started");
Console.WriteLine("Server: Waiting for client to connect");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Server: Client connected");
listener.Stop();
Console.WriteLine("Server: Listener stopped");
Console.WriteLine("Server: Sending data");
byte[] buffer = new byte[] { 1, 2, 3, 4, 5 };
using (NetworkStream clientStream = client.GetStream())
clientStream.Write(buffer, 0, buffer.Length);
Console.WriteLine("Server: Sent data");
}
In this example, made as simple as it gets, you have a server accepting a single client to which it sends some data. The client connects, reads the data and then displays it.
A real-life server would spin new threads (or tasks, for async model) to serve the client's request as soon as the client would connect and carry on listening for new connections.

Can I broadcast in a network but exclude myself?

I'm using C# to create a client-server network. I created client successfully but i have an issue with the server. When i broadcast a message to the server it's supposed to send it to other clients as well. The problem is that the server too gets the message then it thinks it's another message and it creates an infinite loop that sends the same message over and over again. Can I broadcast excluding the server?
public void serverThread()
{
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient_rec.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
if (returnData.StartsWith("broad"))
{
UdpClient udpClient_send = new UdpClient();
IPEndPoint RemoteIpEndPoint1 = new IPEndPoint(IPAddress.Broadcast, 8400);
//can i use something else here instead of broadcast to send it to everyone except myself(server)?
udpClient_send.EnableBroadcast = true;
udpClient_send.Send(receiveBytes, receiveBytes.Length, RemoteIpEndPoint1);
udpClient_send.Close();
}
this.SetText(RemoteIpEndPoint.Address.ToString() + ": " + returnData.ToString());
this.SetText2(RemoteIpEndPoint.Address.ToString());
}
}

Broadcasting and receiving messages with UdpClient

I'm playing around with broadcasting and receiving UDP messages.
I have a client and a server that work ok in my machine, but that can't connect across machines.
My server sends messages and my client receives them.
I turned of the firewall on both machines, that can't be the problem.
The server looks like:
var udpclient = new UdpClient();
IPAddress multicastAddress = IPAddress.Parse("239.0.0.222");
udpclient.JoinMulticastGroup(multicastAddress);
var endPoint = new IPEndPoint(multicastAddress, 2222);
while(true)
{
Byte[] buffer = Encoding.Unicode.GetBytes(Dns.GetHostName());
udpclient.Send(buffer, buffer.Length, endPoint);
Console.WriteLine("Broadcasting server hostname: {0}", Dns.GetHostName());
Thread.Sleep(3000);
}
And the client looks like:
var client = new UdpClient { ExclusiveAddressUse = false };
var ipEndPoint = new IPEndPoint(IPAddress.Any, 2222);
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.ExclusiveAddressUse = false;
client.Client.Bind(ipEndPoint);
IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
client.JoinMulticastGroup(multicastaddress);
Byte[] data = client.Receive(ref ipEndPoint);
string strData = Encoding.Unicode.GetString(data);
Console.WriteLine("Received hostname {0} from the server", strData);
Console.WriteLine("I'm done. Press any key to close me.");
Console.ReadLine();
I think the problem is not in the code, but network related.
Any ideas on how to check what's the problem? Thank you in advance
Try connecting them to a same network such as a wifi network.Note: every time you connect to a different network the IP address changes.

Sending and Receiving UDP packets

The following code sends a packet on port 15000:
int port = 15000;
UdpClient udp = new UdpClient();
//udp.EnableBroadcast = true; //This was suggested in a now deleted answer
IPEndPoint groupEP = new IPEndPoint(IPAddress.Broadcast, port);
string str4 = "I want to receive this!";
byte[] sendBytes4 = Encoding.ASCII.GetBytes(str4);
udp.Send(sendBytes4, sendBytes4.Length, groupEP);
udp.Close();
However, it's kind of useless if I can't then receive it on another computer. All I need is to send a command to another computer on the LAN, and for it to receive it and do something.
Without using a Pcap library, is there any way I can accomplish this? The computer my program is communicating with is Windows XP 32-bit, and the sending computer is Windows 7 64-bit, if it makes a difference. I've looked into various net send commands, but I can't figure them out.
I also have access to the computer (the XP one)'s local IP, by being able to physically type 'ipconfig' on it.
EDIT: Here's the Receive function I'm using, copied from somewhere:
public void ReceiveBroadcast(int port)
{
Debug.WriteLine("Trying to receive...");
UdpClient client = null;
try
{
client = new UdpClient(port);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
IPEndPoint server = new IPEndPoint(IPAddress.Broadcast, port);
byte[] packet = client.Receive(ref server);
Debug.WriteLine(Encoding.ASCII.GetString(packet));
}
I'm calling ReceiveBroadcast(15000) but there's no output at all.
Here is the simple version of Server and Client to send/receive UDP packets
Server
IPEndPoint ServerEndPoint= new IPEndPoint(IPAddress.Any,9050);
Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
WinSocket.Bind(ServerEndPoint);
Console.Write("Waiting for client");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0)
EndPoint Remote = (EndPoint)(sender);
int recv = WinSocket.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
Client
IPEndPoint RemoteEndPoint= new IPEndPoint(
IPAddress.Parse("ServerHostName"), 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, RemoteEndPoint);

Categories