I have found this piece of code on the internet: it does not open a server listening on port 11000, as I hoped.
What can be the problem? I normally code in Delphi, so I am little lost. I have made a corresponding client in Delphi, which works.
I am using demo version of C# 2015.
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
//Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("#") > -1)
{
break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Console.WriteLine("\nPress ENTER to continue...");
//Console.Read();
}
The problem might be here: Whats the IP address of ipHostInfo.AddressList[0] ? It might be the loop-back. I never restrict my server endpoint to an ip-adress unless I need to, but then I will specify it in a configfile.
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000);
As per Jeroen's answer, encountered per .NET's Synchronous Server Socket Example. When listening/connecting to localhost, one should rather use
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
instead of
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
Thanks for feedback. I found som other, older code:
TcpListener serverSocket = new TcpListener(11000);
that does the job. I know it is depreciated, but it works, actually.
Related
i want to let 2 c# apps each one is on a separate computer and both connected to the same ADSL router to send messages to each other i know that we have to use Sockets and tried many solutions on the internet but they are all working at the same computer but not working on a separate computers.
i believe that the problem is in the ip addresses but i tried a lot with no good results
is there any simple code to help please
i tried this function on server side
public static void StartServer()
{
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
Console.WriteLine(ipAddress.ToString());
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
// Create a Socket that will use Tcp protocol
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// A Socket must be associated with an endpoint using the Bind method
listener.Bind(localEndPoint);
// Specify how many requests a Socket can listen before it gives Server busy response.
// We will listen 10 requests at a time
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
// Incoming data from the client.
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue...");
Console.ReadKey();
}
and this function in the client side
public static void StartClient()
{
byte[] bytes = new byte[1024];
try
{
// Connect to a Remote server
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
please make sure that your client is connected to the same IP on which server is started. because it seems in your code that your client connecting to host which you getting it from localhost identity. For your testing purpose please hardcode the Server's IP address in your Remoteendpoint. if still the issue same then I will share code to test on a different networks.
Have a large slow feed over a .NET asynchronous socket. Data is coming from instruments so can be 1 row a second (or more). Some times it can just stall.
Using there two examples from MSDN
asynchronous-client-socket-example
asynchronous-server-socket-example
I have a requirement from the socket client stop the transfer from the server mid stream. Each message is pretty small. Do not need to stop mid message. Need to be able to stop the loop - can receive 1000s of small messages (to client).
My thought is to save a reference to client and call:
client.Shutdown(SocketShutdown.Both);
client.Close();
Is this the correct approach?
private static Socket client;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com"); Dns.GetHostName()
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
//client = new Socket(ipAddress.AddressFamily,
// SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I went to request to open socket from web service to be like notification when the database change . The client is request to web service when it's connection to internet to apply to web service to get his IP Address then web service can send in this IP socket when database change . And client have socket open response the request .
Code of web service in Remote host
[WebMethod]
public string GetMyIpAddress()
{
string adree = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; //get client request ip address
byte[] bytes = new byte[1024];
try
{
IPAddress ipaddress = IPAddress.Parse(adree);
IPEndPoint remote = new IPEndPoint(ipaddress, 1093);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remote);
byte[] meg = Encoding.ASCII.GetBytes("This is a test<EOF>"); // send message to client in it's ip address
int bytesend = sender.Send(meg);
int byterecive = sender.Receive(bytes);
string red = Encoding.ASCII.GetString(bytes, 0, byterecive);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
return(red);
}
catch (Exception e)
{
return(e.ToString());
}
}
Code of client socket
class Program
{
public static string data = null;
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
IPHostEntry iphostinfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipaddress = iphostinfo.AddressList[0];
IPEndPoint localendpoint = new IPEndPoint(ipaddress, 1093);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localendpoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket hander = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytsize = hander.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytsize);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] meg = Encoding.ASCII.GetBytes(data);
hander.Send(meg);
hander.Shutdown(SocketShutdown.Both);
hander.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
The problem when i request to web service to get my client IP address and send to this IP address for test i get this problem :
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or est ablished connection failed because connected host has failed to respond 41.218.1
9.226:1093
Please help me how can solve this problem ?
If we run the code below the output will be
Connecting to www.google.com
30 bytes were sent.
Connecting to www.google.com
We failed to connect!
Connecting to www.google.se
30 bytes were sent.
Why can't i connect to the same host multiple times using the same socket?
(Also the socket seems to have some sort of memory its not just the latest host it remembers all of them...)
static void Main(string[] args)
{
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
client.SendTimeout = 500;
Connect(client, "www.google.com");
Connect(client, "www.google.com");
Connect(client, "www.google.se");
Console.ReadKey();
}
private static void Connect(Socket client, string hostName)
{
Console.WriteLine("Connecting to " + hostName);
IPHostEntry ipHost = Dns.GetHostEntry(hostName);
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 80);
// Connect the socket to the remote end point.
//client.Connect(ipEndPoint);
IAsyncResult ar = client.BeginConnect(ipEndPoint, null, null);
ar.AsyncWaitHandle.WaitOne(5000);
if (!client.Connected)
{
Console.WriteLine("We failed to connect!");
return;
}
// Send some data to the remote device.
string data = "This is a string of data <EOF>";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int bytesTransferred = client.Send(buffer);
// Write to the console the number of bytes transferred.
Console.WriteLine("{0} bytes were sent.", bytesTransferred);
// Release the socket.
//client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
if (client.Connected)
Console.WriteLine("We failed to disconnect");
}
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);