C# Client/Server Socket Connection

Status
Not open for further replies.

cgworld

Active Member
566
2010
9
0
Hello
I am creating a Client/Server app.
I made all the classes but however when i have multi-threads exceptions are given, there is something wrong with my multicon... any tips ?
 
Last edited:
5 comments
Fairly simple. Here's a 5-minute multi-threaded example I made:

Server source:
PHP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Hyperz.TcpExample.Server
{
    public class Program
    {
        // config
        private static IPAddress ip = IPAddress.Any;
        private static short port = 8000;
        // end of config

        private static Thread thread;
        private static TcpListener listener;

        static void Main(string[] args)
        {
            Console.Title = "TCP Server";

            listener = new TcpListener(ip, port);
            thread = new Thread(worker);

            // start the listening thread
            thread.Start();
        }

        static void worker()
        {
            // listen...
            listener.Start();

            Console.WriteLine("Waiting for clients!");

            while (true)
            {
                // wait for a client to connect
                TcpClient client = listener.AcceptTcpClient();

                // client connected
                Console.WriteLine("Client {0:x} connected...", client.GetHashCode());

                // launch a thread to handle it
                ThreadPool.QueueUserWorkItem(tcpClient =>
                {
                    var theClient = (TcpClient)tcpClient;
                    var stream = theClient.GetStream();

                    var bufferSize = 4096;
                    var buffer = new byte[bufferSize];
                    int count;

                    // read the client data
                    while (true)
                    {
                        count = 0;

                        try
                        {
                            count = stream.Read(buffer, 0, bufferSize);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error while reading client data: " + ex.Message);
                            break;
                        }

                        if (count > 0)
                        {
                            // print the data to the console
                            Console.WriteLine("{0:x} says: {1}", theClient.GetHashCode(),
                                Encoding.ASCII.GetString(buffer, 0, count));
                        }
                        else break;
                    }

                    stream.Close();
                    theClient.Close();

                }, client);
            }
        }
    }
}

Client source:
PHP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Hyperz.TcpExample.Client
{
    public class Program
    {
        // config
        private static string ip = "127.0.0.1";
        private static short port = 8000;
        // end of config

        private static TcpClient client;
        private static IPEndPoint endPoint;

        static void Main(string[] args)
        {
            Console.Title = "TCP Client";

            endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            client = new TcpClient();

            // connect to our server
            try
            {
                client.Connect(endPoint);
            }
            catch
            {
                Console.WriteLine("Could not connect to the server :(");
                Console.Read();
                return;
            }

            var stream = client.GetStream();
            string msg;
            byte[] buffer;

            // Send messages to the server
            while (true)
            {
                Console.Write("Message: ");
                msg = Console.ReadLine();

                if (!String.IsNullOrWhiteSpace(msg))
                {
                    buffer = Encoding.ASCII.GetBytes(msg);

                    stream.Write(buffer, 0, buffer.Length);
                    stream.Flush();
                }
                else break;
            }

            stream.Close();
            client.Close();

            Console.WriteLine("Connection closed.");
            Console.Read();
        }
    }
}

Screeny:
[slide]http://i.imgur.com/4UtIv.png[/slide]
 
Status
Not open for further replies.
Back
Top