I have a socket server (written on C++) which receives requests from clients and sends responses back. So, my test client application (C#) is very simple:
try {
UdpClient udpClient = new UdpClient(10241);
// Connect
udpClient.Connect(server_ip_address, 10240);
// prepare the packet to send
iWritableBuff wbuff = new iWritableBuff();
[ ... ]
// Send
udpClient.Send(wbuff.GetBuff(), (int)wbuff.Written());
// Receive a response
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
Console.WriteLine("We've got some data from the server!!! " + receiveBytes.Length + " bytes.");
udpClient.Close();
} catch (Exception e) {
Console.WriteLine("ERROR: " + e.ToString());
}
I run both applications on the same computer. Server receives a request to port 10240 from the client port 10241 and sends a response back to client port 10241, but client never receive it. So, I'm sure that server sends packet back, because everything works perfectly with C++ client. It means that I'm, doing something wrong on my C# client. Any idea?
Thanks!
P.S.> Just test it with Berkley Socket C# client:
try {
// Create socket
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Bind
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
s.Bind(myEP);
// prepare the packet to send
iWritableBuff wbuff = new iWritableBuff();
[ ... ]
// Send it
IPEndPoint sEP = new IPEndPoint(IPAddress.Parse(server_ip_address), 10240);
int res = s.SendTo(wbuff.GetBuff(), (int)wbuff.Written(), 0, sEP);
// Receive the response
byte[] receiveBytes = new Byte[1024];
EndPoint recEP = new IPEndPoint(IPAddress.Any, 0);
res = s.ReceiveFrom(receiveBytes, ref recEP);
Console.WriteLine("We've got some data from the server!!! " + res + " bytes.");
} catch (Exception e) {
Console.WriteLine("ERROR: " + e.ToString());
}
And it works perfect! What's is wrong with UdpSocket?
Not sure if this applies to UDPClients that don't broadcast packets but simply send one to a specified address, but I ran into a similar roadblock.
I had a UDPClient that broadcasted a udp packet for discovery of some custom machines on our network. When I tried to receive the message that the servers would simply echo back, it would not receive the information and would timeout. Turns out that if you use a UDPClient that broadcasts a message out, it WILL NOT be able to receive messages back. It's not documented anywhere, except for one forum topic on msdn that I luckily came across.
The solution was to send the message, immediately close the socket, open a NEW UDPClient on the same port, then use this new UDPClient to receive the echoed back UDP packet. Very annoying.
Give that a shot and see if it works. It definitely works for sending out a broadcasted packet.
Related
We are using C# Socket in Unity to connect to our server. Using proxy is crucial for our use case, unfortunately there is no direct support for proxy in Socket. We are using both TCP and UDP sockets at the same time to exchange data between our app and the server.
Based on this question I'm able to connect through the proxy with first TCP socket, but when I try to connect through the same proxy with second UDP socket, I receive this exception on line socket.Receive(receiveBuffer):
System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host.
ErrorCode = 10054
SocketErrorCode = ConnectionReset
Does it means that the first TCP ws closed because ther can be only one connection at the same time?
I'm using Fiddler to test this scenario. I do not see the second UDP connection in its log.
Is it possible to connect through single proxy with more than one socket from the same app (process)?
Is there some settings in Fiddler that should be changed? Am I missing something?
My simplified code:
class ConnectorExample
{
public class ProxyConfig
{
public string server; // http://127.0.0.1:8888
public string username;
public string password;
public Uri serverUri => new Uri(server);
}
void Connect(IPAddress ipAddress, int tcpPort, int udpPort, ProxyConfig proxyConfig)
{
IPEndPoint remoteTcpEndPoint = new IPEndPoint(ipAddress, tcpPort);
IPEndPoint remoteUdpEndPoint = new IPEndPoint(ipAddress, udpPort);
Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket udpSocket = new Socket(tcpSocket.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
// TCP socket
ConnectThroughProxy(proxyConfig, tcpSocket, remoteTcpEndPoint);
// UDP Socket
// Bind UDP to a free port
udpSocket.Bind(new IPEndPoint(((IPEndPoint) tcpSocket.LocalEndPoint).Address, 0));
ConnectThroughProxy(proxyConfig, udpSocket, remoteUdpEndPoint);
}
// Returns true if connection through the proxy succeeded
private bool ConnectThroughProxy(ProxyConfig proxyConfig, Socket socket, IPEndPoint destination)
{
Uri proxyUri = proxyConfig.serverUri;
string username = proxyConfig.username;
string password = proxyConfig.password;
// Connect to the proxy
socket.Connect(proxyUri.Host, proxyUri.Port);
// Authentication
string auth = string.Empty;
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
auth = $"Proxy-Authorization: Basic {credentials}";
}
// Connect to the destination
// string connectString = $"CONNECT {destination.Address}:{destination.Port} HTTP/1.1{Environment.NewLine}{auth}{Environment.NewLine}{Environment.NewLine}";
string hostAddress = $"{destination.Address}:{destination.Port}";
string connectString = $"CONNECT {destination.Address}:{destination.Port} HTTP/1.1{Environment.NewLine}Host: {hostAddress}{Environment.NewLine}{auth}{Environment.NewLine}{Environment.NewLine}";
byte[] connectMessage = Encoding.UTF8.GetBytes(connectString);
socket.Send(connectMessage);
byte[] receiveBuffer = new byte[1024];
int received = socket.Receive(receiveBuffer); // Exception for second UDP socket
string response = ASCIIEncoding.ASCII.GetString(receiveBuffer, 0, received);
// Response content sample:
// HTTP/1.1 200 Connection Established
// TODO: Should we check for string: "HTTP/1.1 200" ? Checking just "200" seems to be quite weak check.
bool connected = response.Contains("200");
return connected;
}
}
EDIT:
Perhaps the correct question is: Is it possible to use proxy for UDP connections?
I'm trying to create a little program in c# to deal with the xiaomi smart home api.
Api translation
I'm stuck at the beginning. I don't achieve to send {"cmd" : "get_id_list"} to the gateway and receive the response.
I'm trying to use this code to send but I've got nothong in response :
string i = "{\"cmd\" : \"get_id_list\"}";
UdpClient client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.112"), 9898);
Byte[] buffer = null;
buffer = Encoding.Unicode.GetBytes(i.ToString());
client.Send(buffer, buffer.Length, ep);
byte[] b2 = client.Receive(ref ep);
string str2 = System.Text.Encoding.ASCII.GetString(b2, 0, b2.Length);
192.168.1.112 is my gateway ip adress.
Here a screenshot of packet senders software on windows : Screenshot
We can see that the gateway reply to me the right informations.
So how to get this reply whatever the response port ?
thank for your help
As #jdweng suggests, you need to use a Connect() method on your UDP client, or it won't listen for responses. You can either do this, or use two separate UdpClients, one to send and one to receive.
string i = "{\"cmd\" : \"get_id_list\"}";
UdpClient client = new UdpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.112"), 9898));
Byte[] buffer = null;
buffer = Encoding.Unicode.GetBytes(i.ToString());
client.Send(buffer, buffer.Length, ep);
byte[] b2 = client.Receive(ref ep);
string str2 = System.Text.Encoding.ASCII.GetString(b2, 0, b2.Length);
I am currently writing a client-server application. The client sends a UDP broadcast message out trying to locate a server, the server sends a UDP broadcast message out identifying its location.
When a client receives a message identifying the servers location it attempts to connect to the server using socket.Connect(remoteEndPoint).
The server listens for these TCP requests on a listening socket and accepts the requests using listensocket.accept(). The clients details get stored in array (including their IP and port number)
The client sends a message to the server with information about the username and password the user entered.
The server checks the database for the username and password and depending on the result sends back a TCP message (this is where it breaks) to the client who sent the request to check the U&P using the listening socket. I am trying to use the below code to send the TCP message but it will not work as i get an error.
TCPSocket.SendTo(message, clientsArray[i].theirSocket.RemoteEndPoint);
I'm not sure about what method you are using.
But in C# there are 2 common classes that can use as server : TcpClient & Socket
in TcpClient
...
//Start Server
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
//Accept Client
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
String data = "Message From Server";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//Send to Client
stream.Write(msg, 0, msg.Length);
...
and in Socket using TCP
...
//Start Server
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
IPEndPoint ep = new IPEndPoint(hostIP, port);
listenSocket.Bind(ep);
listenSocket.Listen(backlog);
//Accept Client
Socket handler = listener.Accept();
String data = "Message From Server";
byte[] msg = Encoding.ASCII.GetBytes(data);
//Send to Client
handler.Send(msg);
...
and in Socket using UDP
You shouldn't use this on your server since you are using TCP
...
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);
Socket s = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
String data = "Message From Server";
byte[] msg = Encoding.ASCII.GetBytes(data);
//Send to Client by UDP
s.SendTo(msg, endPoint);
...
Normally, when you get a connection from a client, you'll get a TcpClient. That class has a method GetStream(). If you like to send some data to that client, simply write your desired data to that stream.
I am using WebSockets and trying to set up a code base for my server-client. I know how to send messages from client to server and I also know how to listen those messages from the server side.
However, how can I send a message back to a client ?
// here is the _clientSocket that I accepted
_clientSocket = _serverSocket.Accept();
int received = _clientSocket.Receive(_buffer, 0, _buffer.Length,
SocketFlags.None);
// here is the message I got from the client
string receivedMsg = Encoding.ASCII.GetString(_buffer);
if (receivedMsg == "1")
//TO DO: send back to client "This is a test message from server".
Basically you have to use the SendAsync method:
var sendbuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Whatever text you want to send"));
await socket.SendAsync(sendbuffer , WebSocketMessageType.Text, true, CancellationToken.None)
.ConfigureAwait(false);
Take a look at this example: https://stackoverflow.com/a/26274839/307976
You have to call:
_clientsocket.Send(...);
im making a Window Application in C# using Socket Programming. I have developed a Server & a Client. Both are working fine but the problem which im gettin is that when ever i send any message from CLIENT, its send perfectly and receives on SERVER but whenever i try to send any message from SERVER it doesn't send to Client, since at the beginning when a connection is built, server sends the message to client that "Connection Established" and received at Client perfectly,but later on server does not send any message to client!!! Could anyone please help me out ???????
Regards
Umair
EDIT:
//Code at SERVER for SENDING...
private void button_send(object sender, EventArgs e)
{
string input = textBoxWrite.Text;
byte[] SendData = new byte[1024];
ASCIIEncoding encoding = new ASCIIEncoding();
SendData = encoding.GetBytes(input);
client.Send(SendData,SendData.Length,SocketFlags.None);
textBoxShow.Text = "Server: " + input;
}
//Code at CLIENT for receiving
NetworkStream networkStream = new NetworkStream(server);
string input = textBoxUser.Text + ": " + textBoxWrite.Text;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] inputByte = encoding.GetBytes(input);
if (networkStream.CanWrite)
{
networkStream.Write(inputByte, 0, inputByte.Length);
textBoxShow.Text = textBoxShow.Text + Environment.NewLine + input;
textBoxWrite.Text = "";
networkStream.Flush();
}
I'm not sure how best to help based on the information you've provided, but perhaps you could look at something like this example of C# socket programming and compare with your own application.