Pareidolia
Pareidolia

Reputation: 199

Server/Client Socket connection

I am trying to send data from client to server over socket connection. I succesfully sent first data but when i try to send second one it never sends and when i try to send third one it gives me Sockets.SocketException How can I solve that?

Server

byte[] buffer = new byte[1000];


        IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = iphostInfo.AddressList[0];
        IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 8080);

        Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


        sock.Bind(localEndpoint);
        sock.Listen(5);



        while (true) {
            Socket confd = sock.Accept();

            string data = null;

            int b = confd.Receive(buffer);

            data += Encoding.ASCII.GetString(buffer, 0, b);

            Console.WriteLine("" + data);

            confd.Close();
        }

Client

byte[] data = new byte[10];

        IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAdress = iphostInfo.AddressList[0];
        IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 8080);

        Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


        try {

            client.Connect(ipEndpoint);
            Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());


            while (true) {

                string message = Console.ReadLine();
                byte [] sendmsg = Encoding.ASCII.GetBytes(message);
                int n = client.Send(sendmsg);
            }


        }
        catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("Transmission end.");
        Console.ReadKey();

Upvotes: 3

Views: 4904

Answers (1)

Pareidolia
Pareidolia

Reputation: 199

Okay, what a silly mistake. Here is the solution, we should accept socket once.

while (true) {
    Socket confd = sock.Accept();
    string data = null;
    int b = confd.Receive(buffer);
    data += Encoding.ASCII.GetString(buffer, 0, b);
    Console.WriteLine("" + data);
    confd.Close();
}

Changed to

Socket confd = sock.Accept();
while (true) {
    //Socket confd = sock.Accept();
    string data = null;
    int b = confd.Receive(buffer);
    data += Encoding.ASCII.GetString(buffer, 0, b);
    Console.WriteLine("" + data);
    //confd.Close();
}

If there any documentation about sockets, comment it please. I would like to read.

Upvotes: 2

Related Questions