I know this is a total newb question but I'm a beginner programmer trying to learn how to work with sockets and network programming in general with C# and .Net.
I'm working on a tcp echo client and server, two separate apps which I have programmed and run side by side. They work fine except that everytime the server accepts a connection, it echos all the bytes to the client and then gets a SocketException error: <i>10060: 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.</i>
Here is the code...
class TCPEchoServer
{
static void Main(string[] args)
{
const int MAX_BUFF_SIZE = 1024;
const int BACKLOG = 5;
const int TIMEOUT = 3000;
const int LISTEN_PORT = 7;
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, TIMEOUT);
try
{
server.Bind(new IPEndPoint(IPAddress.Any, LISTEN_PORT));
server.Listen(BACKLOG);
Console.WriteLine("The server is now listening on port {0}...", LISTEN_PORT);
}
catch (SocketException se)
{
Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
server.Close();
}
for (; ;)
{
Socket client = null;
byte[] rcvBuffer = new byte[MAX_BUFF_SIZE];
int bytesRead = 0, totalBytes = 0;
try
{
client = server.Accept();
Console.WriteLine("Handling connection from {0}...", client.RemoteEndPoint);
while ((bytesRead = client.Receive(rcvBuffer, totalBytes, 1, SocketFlags.None)) > 0)
{
client.Send(rcvBuffer, totalBytes, 1, SocketFlags.None);
totalBytes += bytesRead;
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Sent {0} bytes: {1}", totalBytes, Encoding.ASCII.GetString(rcvBuffer));
client.Close();
}
catch (SocketException se)
{
Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
client.Close();
}
}
}
}
class TCPEchoClient
{
static void Main(string[] args)
{
const int SEND_PORT = 7;
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint localIP = new IPEndPoint(IPAddress.Loopback, SEND_PORT);
byte[] sendBuffer = Encoding.ASCII.GetBytes("Th");
byte[] rcvBuffer = new byte[sendBuffer.Length];
int bytesRead = 0, totalBytes = 0;
try
{
client.Connect(localIP);
Console.WriteLine("Connected to {0} on port {1}...", localIP.Address, localIP.Port);
client.Send(sendBuffer, 0, sendBuffer.Length, SocketFlags.None);
while ((bytesRead = client.Receive(rcvBuffer, totalBytes, rcvBuffer.Length - totalBytes, SocketFlags.None)) > 0)
{
totalBytes += bytesRead;
}
Console.WriteLine("Received {0} bytes: {1}", totalBytes, Encoding.ASCII.GetString(rcvBuffer));
client.Close();
}
catch (SocketException se)
{
Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
client.Close();
}
}
}
Any help is very appreciated....thanks