C#.NET Socket Programming: Connecting to remote computers.
Posted
by Gio Borje
on Stack Overflow
See other posts from Stack Overflow
or by Gio Borje
Published on 2010-04-06T22:27:39Z
Indexed on
2010/04/06
22:33 UTC
Read the original article
Hit count: 577
I have a typical server in my end and a friend using a client to connect to my IP/Port and he consistently receives the exception: "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 {MY_IP}:{MY_PORT}"—You don't need to know my IP.
The client and server, however, work fine on the loopback address (127.0.0.1). I also do not have any firewall nor is windows firewall active.
Server:
static void Main(string[] args)
{
Console.Title = "Socket Server";
Console.WriteLine("Listening for messages...");
Socket serverSock = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress serverIP = IPAddress.Any;
IPEndPoint serverEP = new IPEndPoint(serverIP, 33367);
SocketPermission perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "98.112.235.18", 33367);
serverSock.Bind(serverEP);
serverSock.Listen(10);
while (true)
{
Socket connection = serverSock.Accept();
Byte[] serverBuffer = new Byte[8];
String message = String.Empty;
while (connection.Available > 0)
{
int bytes = connection.Receive(
serverBuffer,
serverBuffer.Length,
0);
message += Encoding.UTF8.GetString(
serverBuffer,
0,
bytes);
}
Console.WriteLine(message);
connection.Close();
}
}
Client:
static void Main(string[] args)
{
// Design the client a bit
Console.Title = "Socket Client";
Console.Write("Enter the IP of the server: ");
IPAddress clientIP = IPAddress.Parse(Console.ReadLine());
String message = String.Empty;
while (true)
{
Console.Write("Enter the message to send: ");
// The messsage to send
message = Console.ReadLine();
IPEndPoint clientEP = new IPEndPoint(clientIP, 33367);
// Setup the socket
Socket clientSock = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// Attempt to establish a connection to the server
Console.Write("Establishing connection to the server... ");
try
{
clientSock.Connect(clientEP);
// Send the message
clientSock.Send(Encoding.UTF8.GetBytes(message));
clientSock.Shutdown(SocketShutdown.Both);
clientSock.Close();
Console.Write("Message sent successfully.\n\n");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
© Stack Overflow or respective owner