Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9243761
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T08:52:44+00:00 2026-06-18T08:52:44+00:00

Morning, I’ve a TCP Server and a TCP Client. Here’s the code of the

  • 0

Morning, I’ve a TCP Server and a TCP Client.
Here’s the code of the server:

public static class Server
{
    private static IPEndPoint endPoint;

    private static TcpListener tcpServer;
    private static List<Client> clients;
    private static Thread threadListen;

    private static ASCIIEncoding encoding;

    public static void Initialize(IPAddress allowedIPAddress, int port)
    {
        endPoint = new IPEndPoint(allowedIPAddress, port);

        tcpServer = new TcpListener(endPoint);
        clients = new List<Client>();
        threadListen = new Thread(new ThreadStart(Listen));

        encoding = new ASCIIEncoding();
    }

    public static void Start()
    {
        threadListen.Start();
    }

    public static byte[] PacketToArray(Packet packet)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();

        formatter.Serialize(stream, packet);
        byte[] packetArray = stream.GetBuffer();

        stream.Close();

        return packetArray;
    }

    public static Packet ArrayToPacket(byte[] array)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(array);

        Packet packet = new Packet();
        packet = (Packet) formatter.Deserialize(stream);

        stream.Close();

        return packet;
    }

    public static void Send(Client target, Packet packet)
    {
        byte[] packetArray = PacketToArray(packet);

        target.networkStream.Write(packetArray, 0, packetArray.Length);
        target.networkStream.Flush();
        OnSend(packet);
    }

    private static void Listen()
    {
        tcpServer.Start();

        while (true)
        {
            try
            {
                Client client = new Client();
                client.tcpClient = tcpServer.AcceptTcpClient();
                client.networkStream = client.tcpClient.GetStream();
                client.thread = new Thread(new ParameterizedThreadStart(HandleCommunication));

                clients.Add(client);
                client.thread.Start(client);
                OnJoin(client);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                break;
            }
        }
    }

    private static void HandleCommunication(object client)
    {
        Client handleClient = (Client) client;

        byte[] messageBuffer = new byte[4096];
        int bytesRead = 0;

        while (true)
        {
            bytesRead = 0;

            try
            {
                bytesRead = handleClient.networkStream.Read(messageBuffer, 0, messageBuffer.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                break;
            }

            if (bytesRead == 0)
            {
                clients.Remove(handleClient);
                OnLeave(handleClient);
                break;
            }

            Packet packet = ArrayToPacket(messageBuffer);
            OnReceive(packet);
        }
    }

    private static void OnStart()
    {
        Console.WriteLine("Server started on port .");
    }

    private static void OnJoin(Client client)
    {
        Console.WriteLine("Client [ID] connected.");

        Send(client, PacketGenerator.Generate(OpCodes.opHandshake, null));
    }

    private static void OnLeave(Client client)
    {
        Console.WriteLine("Client [ID] disconnected.");
    }

    private static void OnSend(Packet packet)
    {
        Console.WriteLine("Server: " + packet.opcode.ToString() + " | " + packet.message);
    }

    private static void OnReceive(Packet packet)
    {
        Console.WriteLine("Client [ID]: " + packet.opcode.ToString() + " | " + packet.message);
    }

    public struct Client
    {

        public TcpClient tcpClient;
        public NetworkStream networkStream;
        public Thread thread;

    }

}

And here’s the code of the client:

[Serializable]
public struct Packet
{

    public int opcode;
    public string message;

}

public static class Client
{

    private static IPEndPoint endPoint;

    private static TcpClient tcpClient;
    private static NetworkStream networkStream;
    private static Thread threadCommunication;

    private static ASCIIEncoding encoding;

    public static void Initialize(string ipAddress, int port)
    {
        endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        tcpClient = new TcpClient();
        networkStream = null;
        threadCommunication = new Thread(new ThreadStart(HandleCommunication));

        encoding = new ASCIIEncoding();
    }

    public static void Connect()
    {
        tcpClient.Connect(endPoint);
        threadCommunication.Start();
        Console.WriteLine("Connected to server.");

        networkStream = tcpClient.GetStream();
    }

    public static byte[] PacketToArray(Packet packet)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();

        formatter.Serialize(stream, packet);
        byte[] packetArray = stream.GetBuffer();

        stream.Close();

        return packetArray;
    }

    public static Packet ArrayToPacket(byte[] array)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(array);

        Packet packet = new Packet();
        packet = (Packet)formatter.Deserialize(stream);

        stream.Close();

        return packet;
    }

    public static void Send(Packet packet)
    {
        byte[] packetArray = PacketToArray(packet);

        networkStream.Write(packetArray, 0, packetArray.Length);
        networkStream.Flush();
        OnSend(packet);
    }

    private static void HandleCommunication()
    {
        byte[] messageBuffer = new byte[4096];
        int bytesRead = 0;

        while (true)
        {
            bytesRead = 0;

            try
            {
                bytesRead = networkStream.Read(messageBuffer, 0, messageBuffer.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                break;
            }

            if (bytesRead == 0)
            {
                Console.WriteLine("Connection closed.");
                break;
            }

            Packet packet = ArrayToPacket(messageBuffer);
            OnReceive(packet);
        }
    }

    private static void OnSend(Packet packet)
    {
        Console.WriteLine("Client [ID]: " + packet.opcode.ToString() + " | " + packet.message);
    }

    private static void OnReceive(Packet packet)
    {
        Console.WriteLine("Server: " + packet.opcode.ToString() + " | " + packet.message);

        switch (packet.opcode)
        {

            case OpCodes.opHandshake:
                Send(PacketGenerator.Generate(OpCodes.opHandshake, null));
                break;

        }
    }

}

But when I’m sending a packet from the server to the client (handshake) the client get’s an exception in the “ArrayToPacket” function at “packet = (Packet) formatter.Deserialize(stream);”
The exact message is: The assembly “ComDee, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null” could’nt be found.
(ComDee is the assembly where the server runs).

Why? The packet-structure of the client is the same as the structrue of the server.

UPDATE

I’ve edited the Server and Client class and used protobuf-net.
But the “OnReceive” in the Client-Class doesn’t get called.
Where is the problem?
Server-Class:

[ProtoContract]
public struct Packet
{

    [ProtoMember(1)] public int opcode;
    [ProtoMember(2)] public string message;

}

public static class Server
{

    private static IPEndPoint endPoint;

    private static TcpListener tcpServer;
    private static List<Client> clients;
    private static Thread threadListen;

    private static ASCIIEncoding encoding;

    public static void Initialize(IPAddress allowedIPAddress, int port)
    {
        endPoint = new IPEndPoint(allowedIPAddress, port);

        tcpServer = new TcpListener(endPoint);
        clients = new List<Client>();
        threadListen = new Thread(new ThreadStart(Listen));

        encoding = new ASCIIEncoding();
    }

    public static void Start()
    {
        threadListen.Start();
    }

    public static byte[] PacketToArray(Packet packet)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();

        Serializer.Serialize<Packet>(stream, packet);
        byte[] packetArray = stream.GetBuffer();

        stream.Close();

        return packetArray;
    }

    public static Packet ArrayToPacket(byte[] array)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(array);

        Packet packet = new Packet();
        packet = Serializer.Deserialize<Packet>(stream);

        stream.Close();

        return packet;
    }

    public static void Send(Client target, Packet packet)
    {
        byte[] packetArray = PacketToArray(packet);

        target.networkStream.Write(packetArray, 0, packetArray.Length);
        target.networkStream.Flush();
        OnSend(packet);
    }

    private static void Listen()
    {
        tcpServer.Start();
        OnStart();

        while (true)
        {
            try
            {
                Client client = new Client();
                client.tcpClient = tcpServer.AcceptTcpClient();
                client.networkStream = client.tcpClient.GetStream();
                client.thread = new Thread(new ParameterizedThreadStart(HandleCommunication));

                clients.Add(client);
                client.thread.Start(client);
                OnJoin(client);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                break;
            }
        }
    }

    private static void HandleCommunication(object client)
    {
        Client handleClient = (Client) client;

        byte[] messageBuffer = new byte[4096];
        int bytesRead = 0;

        while (true)
        {
            bytesRead = 0;

            try
            {
                bytesRead = handleClient.networkStream.Read(messageBuffer, 0, messageBuffer.Length);
            }
            catch
            {
                clients.Remove(handleClient);
                OnLeave(handleClient);
                break;
            }

            if (bytesRead == 0)
            {
                Packet packet = ArrayToPacket(messageBuffer);
                OnReceive(packet);
            }
        }
    }

    private static void OnStart()
    {
        Console.WriteLine("Server started.");
    }

    private static void OnJoin(Client client)
    {
        Console.WriteLine("Client [ID] connected.");

        Send(client, PacketGenerator.Generate(OpCodes.opHandshake, null));
    }

    private static void OnLeave(Client client)
    {
        Console.WriteLine("Client [ID] disconnected.");
    }

    private static void OnSend(Packet packet)
    {
        Console.WriteLine("Server: " + packet.opcode.ToString() + " | " + packet.message);
    }

    private static void OnReceive(Packet packet)
    {
        Console.WriteLine("Client [ID]: " + packet.opcode.ToString() + " | " + packet.message);
    }

    public struct Client
    {

        public TcpClient tcpClient;
        public NetworkStream networkStream;
        public Thread thread;

    }

}

And here is the Client-Class:

[ProtoContract]
public struct Packet
{

    [ProtoMember(1)]
    public int opcode;
    [ProtoMember(2)]
    public string message;

}

public static class Client
{

    private static IPEndPoint endPoint;

    private static TcpClient tcpClient;
    private static NetworkStream networkStream;
    private static Thread threadCommunication;

    private static ASCIIEncoding encoding;

    public static void Initialize(string ipAddress, int port)
    {
        endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        tcpClient = new TcpClient();
        networkStream = null;
        threadCommunication = new Thread(new ThreadStart(HandleCommunication));

        encoding = new ASCIIEncoding();
    }

    public static void Connect()
    {
        tcpClient.Connect(endPoint);
        threadCommunication.Start();
        Console.WriteLine("Connected to server.");

        networkStream = tcpClient.GetStream();
    }

    public static byte[] PacketToArray(Packet packet)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();

        Serializer.Serialize<Packet>(stream, packet);
        byte[] packetArray = stream.GetBuffer();

        stream.Close();

        return packetArray;
    }

    public static Packet ArrayToPacket(byte[] array)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(array);

        Packet packet = new Packet();
        packet = Serializer.Deserialize<Packet>(stream);

        stream.Close();

        return packet;
    }

    public static void Send(Packet packet)
    {
        byte[] packetArray = PacketToArray(packet);

        networkStream.Write(packetArray, 0, packetArray.Length);
        networkStream.Flush();
        OnSend(packet);
    }

    private static void HandleCommunication()
    {
        byte[] messageBuffer = new byte[4096];
        int bytesRead = 0;

        while (true)
        {
            bytesRead = 0;

            try
            {
                bytesRead = networkStream.Read(messageBuffer, 0, messageBuffer.Length);
            }
            catch
            {
                Console.WriteLine("Connection closed.");
                break;
            }

            if (bytesRead == 0)
            {
                Packet packet = ArrayToPacket(messageBuffer);
                OnReceive(packet);
            }
        }
    }

    private static void OnSend(Packet packet)
    {
        Console.WriteLine("Client [ID]: " + packet.opcode.ToString() + " | " + packet.message);
    }

    private static void OnReceive(Packet packet)
    {
        Console.WriteLine("Server: " + packet.opcode.ToString() + " | " + packet.message);

        switch (packet.opcode)
        {

            case OpCodes.opHandshake:
                Send(PacketGenerator.Generate(OpCodes.opHandshake, null));
                break;

        }
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T08:52:45+00:00Added an answer on June 18, 2026 at 8:52 am

    Types are scoped by their assembly, and BinaryFormatter serializes the type metadata (the assembly-qualified name, etc). Having a copy of the same class in two places is not enough: they are not the same type unless they came from the same assembly.

    Also note that BinaryFormatter is pretty verbose in what it stores on the wire. If you want something that addresses both of these issues without you needing to do all the serialization manually, then protobuf-net will help:

    • it is very dense on the wire
    • it is not bound to specific types; you can serialize with A and deserialize with B as long as A and B look similar

    For example:

    [ProtoContract]
    public struct Packet {    
        [ProtoMember(1)] public int opcode;
        [ProtoMember(2)] public string message;
    }
    

    and use Serializer.Serialize instead of BinaryFormatter.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Morning stackoverflow, I have a repeater, with the following code in my aspx page;
Morning folks. Novice Rich here once again requesting assistance. I have just started dabbling
Morning all...thicky, newbie Rich here! I have a very simple set up, three different
Morning Everyone!.. General Routing Quesiton Here... I'm currently working to achieve a route similar
morning. I am wanting to take all segments of php code out of a
Morning All, I was hoping someone could help or provide some sample code for
Morning All, I have been writing an ever so simple IRC client in visual
Morning, I would love help with my specific code but if you're busy any
Morning all I have frequently used the old <asp:Label ID=lblWas runat=server Text='<%# XPath(FACEVALUE) %>'></asp:Label>
Morning everyone, I have some code that sorts the direct LIs of a list

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.