Click here to Skip to main content
15,896,912 members
Articles / Programming Languages / XML

A Full Library for a Socket Client/Server System

Rate me:
Please Sign up or sign in to vote.
4.81/5 (42 votes)
14 Jan 2015CPOL5 min read 162.4K   11.3K   149  
My article shows a library that everyone can use to create their socket communication. Also, it explains how the library is developed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AsyncClientServerLib.Server;
using System.Net;
using AsyncClientServerLib.Message;
using SocketServerLib.SocketHandler;
using SocketServerLib.Server;

namespace TestApp
{
    delegate void SetTextCallback(string text);
    
    public partial class FormServer : Form
    {
        private BasicSocketServer server = null;
        private Guid serverGuid = Guid.Empty;

        public FormServer()
        {
            InitializeComponent();
        }

        protected override void OnClosed(EventArgs e)
        {
            if (this.server != null)
            {
                this.server.Dispose();
            }
            base.OnClosed(e);
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            this.serverGuid = Guid.NewGuid();
            this.server = new BasicSocketServer();
            this.server.ReceiveMessageEvent += new SocketServerLib.SocketHandler.ReceiveMessageDelegate(server_ReceiveMessageEvent);
            this.server.ConnectionEvent += new SocketConnectionDelegate(server_ConnectionEvent);
            this.server.CloseConnectionEvent += new SocketConnectionDelegate(server_CloseConnectionEvent);
            this.server.Init(new IPEndPoint(IPAddress.Loopback, 8100));
            this.server.StartUp();
            this.buttonStart.Enabled = false;
            this.buttonStop.Enabled = true;
            this.buttonSend.Enabled = true;
            MessageBox.Show("Server Started");
        }

        void server_CloseConnectionEvent(AbstractTcpSocketClientHandler handler)
        {
            MessageBox.Show(string.Format("A client is disconnected from the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        void server_ConnectionEvent(AbstractTcpSocketClientHandler handler)
        {
            MessageBox.Show(string.Format("A client is connected to the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        void server_ReceiveMessageEvent(SocketServerLib.SocketHandler.AbstractTcpSocketClientHandler handler, SocketServerLib.Message.AbstractMessage message)
        {
            BasicMessage receivedMessage = (BasicMessage)message;
            byte[] buffer = receivedMessage.GetBuffer();
            if (buffer.Length > 1000)
            {
                MessageBox.Show(string.Format("Received a long message of {0} bytes", receivedMessage.MessageLength), "Socket Server", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string s = System.Text.ASCIIEncoding.Unicode.GetString(buffer);
            this.SetReceivedText(s);
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            this.server.Shutdown();
            this.server.Dispose();
            this.server = null;
            this.buttonStart.Enabled = true;
            this.buttonStop.Enabled = false;
            this.buttonStop.Enabled = false;
            MessageBox.Show("Server Stopped");
        }

        private void SetReceivedText(string text)
        {
            if (this.textBoxReceived.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetReceivedText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBoxReceived.Text = text;
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            ClientInfo[] clientList = this.server.GetClientList();
            if (clientList.Length == 0)
            {
                MessageBox.Show("The client is not connected", "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            AbstractTcpSocketClientHandler clientHandler = clientList[0].TcpSocketClientHandler;
            string s = this.textBoxSend.Text;
            byte[] buffer = System.Text.ASCIIEncoding.Unicode.GetBytes(s);
            BasicMessage message = new BasicMessage(this.serverGuid, buffer);
            clientHandler.SendAsync(message);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Mediatech Solutions
Italy Italy
I’m an IT Project Manager for an Italian Betting Company and over the last 2 years I acquired experience in Betting area.
I have developed code in different object oriented languages (C#, C++, Java) for more than 10 years using a set of technology such as .Net, J2EE, multithreading, etc…

Comments and Discussions