Reputation:
I need to make TCPIP server and client apps which will communicate and do some sending of random files. So far, I made this:
Server:
static void Main(string[] args)
{
IPAddress localIP = IPAddress.Parse("127.0.0.1");
TcpListener tcpServerListener = new TcpListener(localIP, 1234);
tcpServerListener.Start();
Console.WriteLine("Service started...");
while (true)
{
var serverSocket = tcpServerListener.AcceptTcpClient();
Console.WriteLine("Request accepted!");
if (serverSocket.Connected)
{
Do(serverSocket);
}
Console.WriteLine("Waiting for new request...");
Console.ReadLine();
}
}
private static void Do(TcpClient serverSocket)
{
var serverSockStream = serverSocket.GetStream();
var reader = new StreamReader(serverSockStream);
var poruka = reader.ReadLine();
var odgovor = "Hello " + poruka;
var writer = new StreamWriter(serverSockStream);
writer.Flush();
reader.Close();
writer.Close();
}
Client:
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
NetworkStream clientSockStream = tcpClient.GetStream();
var writer = new StreamWriter(clientSockStream);
writer.WriteLine("TCP/IP Client");
writer.Flush();
var reader = new StreamReader(clientSockStream);
var odgovor = reader.ReadLine();
Console.WriteLine("Answer received: " + odgovor);
writer.Close();
reader.Close();
}
The problem I am facing is that once I achieve communication, the second response crashes:
Only one usage of each socket address (protocol/network address/port) is normally permitted
So, how to fix this error and later allow sending files? (later with serialization etc.)
Upvotes: 2
Views: 79
Reputation: 63772
Are you sure you're not trying to launch the server multiple times? Unlike the client, the server never exits and the Console.ReadLine
prevents you from receiving another client until you press enter. I assume the old server is still hung in the background while you try to launch a new one, which necessarily fails. Get rid of the ReadLine
, add a proper way to exit the server, and don't run multiple servers at the same time, and you should be fine.
Writing a custom TCP client/server application is very tricky. TCP is still a very low-level protocol, and it likely doesn't work the way you expect it to. If you choose to follow this path, make sure to learn how TCP works first, and learn how to properly handle all the communication states and errors.
Upvotes: 1
Reputation: 4728
Friend, you seem to be re-inventing the wheel here. With all the technologies available to do this, there's no reason why you need to be doing this stuff at the "sockets" level. Far more simpler:
Anything but sockets. You'll waste a lot of time.
Upvotes: 1