As kind of a followup to this question I've gotten a solution working on my local machine, but not on a machine on the network.
I don't know too much about sockets other than that basics, so bear with me. The goal is for a client to look for a server on a local network, and this is the result of some cut/paste/edit code.
This is the client code:
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294);
byte[] data = new byte[1024];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
string welcome = "What's your IP?";
data = Encoding.ASCII.GetBytes(welcome);
client.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
EndPoint tmpRemote = (EndPoint)server;
data = new byte[1024];
int recv = client.ReceiveFrom(data, ref tmpRemote);
this.IP.Text = ((IPEndPoint)tmpRemote).Address.ToString(); //set textbox
this.Port.Text = Encoding.ASCII.GetString(data, 0, recv); //set textbox
client.Close();
}
This is the server code:
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 10294);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
newsock.Bind(ipep);
newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any,IPAddress.Parse("127.0.0.1")));
while (true)
{
Console.WriteLine("Waiting for a client...");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tmpRemote = (EndPoint)(sender);
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "7010";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote);
}
It works find on my local machine (both server and client) but when I try another machine on the same network I get "An existing connection was forcibly closed by the remote host"
I realize I need to add a lot of try/catch but I'm just trying to get a handle on how this works first.
I have to start by saying that I know nothing about C#, but...
Looking at the definition of the ipep in the client code, it looks like you're trying to send your data to yourself, rather than broadcast it (as has been suggested in your other question). The thing that caught my attention was that "127.0.0.1" is the address of "localhost".
That would explain why it works nicely when you're running both the client and server on the one machine, as it will be sending to itself.
I would expect that correct endpoint would be for a broadcast address (eg. "255.255.255.255") - although you could also choose the broadcast address of the local network that you're on, depending on how widely you wish to broadcast.
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10294);
Should become:
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 10294);
And
newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any, IPAddress.Parse("127.0.0.1")));
Should Become
newsock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Any, IPAddress.Parse("255.255.255.255")));
I think.
OK, this doesn't work, so something's still wrong.
Related
I am trying to develop a C# UTP server in order to send a list of string sList. This is continuously filled by another thread. My aspected software behavior is to get a client on the network and send each information.
Here the method:
internal static void MyUDPSocket()
{
byte[] data = new byte[1024];
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9050);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ip);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9050);
EndPoint Remote = (EndPoint)(sender);
while (true)
{
if (sList.Count > 0)
{
try
{
data = Encoding.ASCII.GetBytes(sList[0]);
socket.SendTo(data, data.Length, SocketFlags.None, Remote);
sList.RemoveAt(0);
}
catch (FormatException e) { }
catch (System.ArgumentNullException en) { }
}
}
}
Anyway, when I launch the software, C# return an Exception (System.Net.Sockets.SocketException) on socket.SendTo(data, data.Length, SocketFlags.None, Remote) and it say that there is not a required address in the context.
You are creating a destination address with INADDR_ANY, with a port of 0. You can't do that.
I've tried multiple methods of doing this, and non seem to work out. But there must be a way.
What I'm trying to do (in C#) is create a server. I want the server to listen on a IP and port, and when it connects to a client, I want it to read what the client says, and send a reply. For the client, I want to connect to a server and send data, and receive the reply from the server.
How can I go about doing this?
I've used Microsoft examples and examples found on MSDN. They have Client > data > Server but it doesn't ever seem to include the server reply.
I know this can be done, obviously, because we have multiplayer games.
Thanks for the help.
EDIT - Code snippets
SERVER
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 904);
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newSocket.Bind(endPoint);
Console.WriteLine("Listening for connections...");
//LISTEN FOR CLIENT
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 904);
EndPoint tmpRemote = (EndPoint)sender;
//READ MESSAGE FROM CLIENT
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to server!";
data = Encoding.ASCII.GetBytes(welcome);
//SEND WELCOME REPLY TO CLIENT
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
sock.SendTo(data, tmpRemote);
Console.WriteLine("Reply sent to client");
while (true)
{
if(!newSocket.Connected)
{
Console.WriteLine("Client disconnected.");
break;
}
data = new byte[1024];
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
newSocket.Close();
Console.WriteLine("Server disconnected.");
Console.ReadLine();
}
}
CLIENT
static void Main(string[] args)
{
Console.WriteLine("Message [127.0.0.1:904]: ");
string msg = Console.ReadLine();
byte[] packetData = ASCIIEncoding.ASCII.GetBytes(msg);
string IP = "127.0.0.1";
int port = 904;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
Console.WriteLine("Data sent!");
int recv;
byte[] data = new byte[1024];
EndPoint tmpRemote = (EndPoint)ep;
while(true)
{
//READ MESSAGE FROM SERVER
recv = client.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
client.Close();
Console.WriteLine("Client disconnected.");
Console.ReadLine();
}
I can't get the server to talk back to the client and have the client read/display the server's reply.
change this sentence
sock.SendTo(data, tmpRemote);
to
newSocket.SendTo(data, tmpRemote);
and remove these sentences, you have bind local EndPoint twice.
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
In Net, you can use UdpClient instead of Socket.
If you want a demo, look at this demo.
I have a program that multiple clients would be able to connect to a server using a socket:
private void performConnect()
{
while (true)
{
if (myList.Pending())
{
thrd = thrd + 1;
tcpClient = myList.AcceptTcpClient();
IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
string clientIP = ipEndPoint.Address.ToString();
nStream[thrd] = tcpClient.GetStream();
currentMsg = "\n New IP client found :" + clientIP;
recieve[thrd].Start();
this.Invoke(new rcvData(addNotification));
try
{
addToIPList(clientIP);
}
catch (InvalidOperationException exp)
{
Console.Error.WriteLine(exp.Message);
}
Thread.Sleep(1000);
}
}
}
then the server could send data (chat messages) to a chosen client, using this code.
private void sendData(String data)
{
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding asciidata = new ASCIIEncoding();
byte[] buffer = asciidata.GetBytes(data);
if (nStream.CanWrite)
{
nStream.Write(buffer, 0, buffer.Length);
nStream.Flush();
}
}
the problem is that whatever IP i choose from the combo box, the message i send would always be directed/sent to the last IP that connected to the server.. Please somebody pinpoint my error! all help would be appreciated.
Look at those lines:
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
You are creating a new socket but you are sending the data to the socket stored in the variable tcpClient that is global (since it was not defined in the method), thus totally ignoring the IPEndPoint parsed from the combobox.
You should not create a new socket in order to send data to the clients. Instead, store all clients in a collection and retrieve the appropriate one based on the input of the combobox.
I'm trying to send and receive data to a specific endpoint with local port 50177. Send data does very good, but when the program tries to receive data it can't receive any. When I sniff the network with Wireshark I see that server sent data to me. I know that I can't have 2 UdpClient on one port at the same time.
Can any one help me?
UdpClient udpClient2 = new UdpClient(50177);
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005);
udpClient2.Send(peerto255, peerto255.Length, Ip2);
IPEndPoint Ip = new IPEndPoint(IPAddress.Parse("10.10.240.1"), 1005);
var dgram = udpClient2.Receive(ref Ip);
You can absolutely have two UdpClient on one port but you need to set socket options before you bind it to an endpoint.
private static void SendAndReceive()
{
IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, 1234);
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient receiveClient = new UdpClient();
receiveClient.ExclusiveAddressUse = false;
receiveClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiveClient.Client.Bind(ep1);
byte[] buffer = receiveClient.Receive(ref ep1);
});
UdpClient sendClient = new UdpClient();
sendClient.ExclusiveAddressUse = false;
sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint ep2 = new IPEndPoint(IPAddress.Parse("X.Y.Z.W"), 1234);
sendClient.Client.Bind(ep1);
sendClient.Send(new byte[] { ... }, sizeOfBuffer, ep2);
}
Use the same IPEndPoint for receiving that you used for sending.
UdpClient udpClient2 = new UdpClient(50177);
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005);
udpClient2.Send(peerto255, peerto255.Length, Ip2);
var dgram = udpClient2.Receive(ref Ip2);
I'm working with sockets in C# and I'm getting the following error:
A request to send or receive data was
disallowed because the socket is not
connected and (when sending on a
datagram socket using a sendto call)
no address was supplied
Here is the code that I'm executing:
private void HostSubscriberService()
{
IPAddress ipV4 = PublisherService.ReturnMachineIP();
var localEP = new IPEndPoint(ipV4, _port);
var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEP);
StartListening(server);
}
private void StartListening(Socket server)
{
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
var data = new byte[1024];
int recv = server.ReceiveFrom(data, ref remoteEP);
string messageSendFromClient = Encoding.ASCII.GetString(data, 0, recv);
MessageBox.Show(messageSendFromClient);
}
}
The error happens # int recv = server.ReceiveFrom(data, ref remoteEP);
I just need to listen for new incoming connections and then print the message that was sent from the new client.
I need it to work on the TCP protocol, because some of the messages will be > 1500 bytes
Thanks!
You need to .BeginAccept() before you can receive.
Here's a link with a sinple Asynchronous Socket Server example
ReceiveFrom() is for UDP, use Accept() and Receive() for TCP