Click here to Skip to main content
15,879,239 members
Articles / Programming Languages / C#
Article

Simple Socket Control(s) to Create Server-Client Applications

Rate me:
Please Sign up or sign in to vote.
4.65/5 (21 votes)
5 Jul 2006CPOL5 min read 137.9K   12.1K   51   30
Creating a simple control to be used as socket

Introduction

This simple project can be used instead of TcpClient, TcpListen - socket classes, because it's easy. You can create a server application in just three or four lines of code, and a client application in just two lines of code. This is the main idea of this article.

ConnectionSocket Class

Use this class instead of TcpClient class. Create an instance of it and use the function Connect to connect to a remote endpoint, and Send to send data. When the receive event fires, then there is a data that has been sent to you from the remote endpoint.

  • Connect

    Function used to connect to a remote endpoint.

    • Host

      string, specifies the IP, it can be (e.g. "127.0.0.1") or (e.g. "www.codeproject.com").

    • port

      int, specifies the port in the remote endpoint that there is a socket listening to it.

    • Mode

      One of the ConnectionMode enum, it is recommended to use SyncConnectAsyncRecv, other options can also be used.

  • Bind

    This function is optional to use, use it to bind this socket to a specific endpoint. If you don't use this function the framework will bind the socket for you.

  • Send

    Send the array of bytes to the remote endpoint, use this function for a connected socket only.

  • Receive

    This function is used in Blocking mode, to receive data from the remote endpoint, if there is no data received then the thread will be blocked until the data is made available. (It is not recommended to use this function for receiving data.)

    • Length

      int, the maximum length of the array that can be passed to the buffer. If the received data is greater than the Length, then the returned array will contain only the data of size Length, you must call Receive again to receive the other data. If the received data is less than the Length, then the returned array will be of the size of the data received.

  • Close

    Use this function to close any created socket, for every created socket you must call close socket to close the socket.

  • Shutdown

    Use this function to disable send or receive or both, the param is documented in the MSDN.

  • recieve event

    Fired when there is data available to be received, the RecieveEventArg contains the data and the data length that is received, don't call Recieve in the recieve event, it will receive the next available data.

  • create event

    Fired when the socket is created.

  • connect event

    Fired in non Blocking mode (or AsyncConnectionxxxxxxxxx) when the connection is accepted by the remote endpoint.

  • shutdown event

    Fired when calling the shutdown function.

  • send event

    Fired after the send process ends.

  • close event

    Fired if the close function is called or if the remote endpoint closes the connection or if there is any socket exception received. CloseEventArgs contains the exception and a string that specifies the error. You can use it in a message box.

ListenSocket Class

Use this call, instead of the TcpListen class. You can start listen, stop listen and accept connection from a remote end point.

  • Port

    Use it to set the port to listen to. You must set it before calling start listen.

  • StartListen

    Set the state of the socket to Listening state.

    • IsBlocked

      If true, the accept event will not be fired when there is a request for connection, you must call the Accept function. If false, then the accept event fires.

  • StopListen

    Stop listening.

  • close

    Use this function to close any created socket, for every socket created, you must call close socket to close the socket.

  • Accept

    Use this function if you pass true to StartListen. This function will block the thread, until a remote endpoint request connection is made.

  • create event

    Fired after creating the socket.

  • close event

    Fired if the close function is called or if the remote endpoint closes the connection or if there is any socket exception received. CloseEventArgs contains the exception and a string that specifies the error. You can use it in a message box.

  • accept event

    Fired when a connection is accepted from the remote endpoint. The AcceptEventArgs contains a connected socket that is used to create a connection.

Example

  1. Create a new Windows application project, named SimpleServer.
  2. Right click on the Toolbox - add/remove item.
  3. Click Browse - select sockets.dll (download it from this article).
  4. Click OK.
  5. The two classes ConnectSocket, ListenSocket are now in the Toolbox.

First drag one listen socket and one connect socket to your dialog. Change the port of the listen socket to 4000, from the properties. Change IsBlocked of the connect socket to false. Add a button, name it Listen, and handle the Click event:

C#
private void button1_Click(object sender, System.EventArgs e)
{
  Socket_Listen.StratListen(false);
}

Add a TextBox for sending a message and add a Button named send, to send the text to the client, handle the clicked event:

C#
private void button2_Click(object sender, System.EventArgs e)
{
   byte[] buff = Socktes.ByesConvertor.GetBytes(textBox1.Text);
   Socket_Connection.Send(buff);
}
//You can use Encoding class to get an array of bytes, but the BytesConvertor 
//class has all the functions we need to use in the socket classes.

Add a ListBox to add the received messages.

Let's get to the main code of the project. For the listen socket, handle the accept event:

C#
private void Socket_Listen_accept(object Sender, Socktes.AcceptEventArgs e)
{
    Socket_Connection.SocketHandle = e.ConnectedSocket;
}
// e.ConnectedSocket contain a connected socket, 
// set the Connectsocket instance
// to the Connected socket received from the 
// accept event.

For the connect socket, handle the receive event:

C#
private void Socket_Connection_recieve(object Sender, 
                               Socktes.RecieveEventArgs e)
{
    string s = Socktes.ByesConvertor.BytesToString(e.Data);
    listBox1.Items.Add(s);
}
// recieve the data from the socket and 
// add it to the list box.

That's all the code for the server, now let's go to the client.

Create a new Windows application, named SimpleClient. Drag one connect socket to your form, change IsBlocked to false. Add a Button, name it connect, now handle the Click event:

C#
private void button1_Click(object sender, System.EventArgs e)
{
    Socket_Connection.Connect("127.0.0.1",4000);
}

Add a TextBox and a Button, handle the Click event:

C#
private void button2_Click(object sender, System.EventArgs e)
{
    byte[] b = Socktes.ByesConvertor.GetBytes(textBox1.Text);
    Socket_Connection.Send(b);
}

Add a ListBox, handle the receive event of the connect socket:

C#
private void Socket_Connection_recieve(object Sender, Socktes.RecieveEventArgs e)
{
    string s = Socktes.ByesConvertor.BytesToString(e.Data);
    listBox1.Items.Add(s);
}

That's all about the client and the server. Sorry for not commenting the demo, but Socket.dll is well commented.

License

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


Written By
Team Leader
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUnAccepted connection thow error in ConnectSocket.cs line 320 Pin
Frederic GIRARDIN13-Mar-17 0:23
Frederic GIRARDIN13-Mar-17 0:23 
QuestionInter-Thread unmanaged in test project Pin
Frederic GIRARDIN13-Mar-17 0:19
Frederic GIRARDIN13-Mar-17 0:19 
QuestionClosing Socket Pin
Member 1108393217-Sep-14 5:57
Member 1108393217-Sep-14 5:57 
GeneralMy vote of 5 Pin
AminNz10-Jan-13 9:11
AminNz10-Jan-13 9:11 
QuestionSilverlight and Silverlight for Windows Phone 7.1 Pin
Androyx9-Oct-12 5:52
Androyx9-Oct-12 5:52 
QuestionUdp Pin
moloko91130-Aug-12 6:02
moloko91130-Aug-12 6:02 
Questionhow to catch the end of receive event!? Pin
epidemic9996-Jan-11 3:15
epidemic9996-Jan-11 3:15 
QuestionHow to disconnect from Client? Pin
bravehoang18-May-10 0:16
bravehoang18-May-10 0:16 
I got connect successfully, then, I closed Client application. I open Client application again, and I got exception when try to connect (10056). But if dont click on Connect again, I send data, got error 10057. I want to add button Disconnect, but dont know the command. help me. Thanks.
QuestionWhich version of c# . NET is the project written in? Pin
Daddi9-Jan-10 6:23
Daddi9-Jan-10 6:23 
GeneralVB 2008 Pin
MikePem2-Nov-09 5:52
MikePem2-Nov-09 5:52 
GeneralNice One Pin
Rascal29-May-08 6:43
Rascal29-May-08 6:43 
QuestionCan this be used in an MFC app? Pin
Andre Oliveira13-Sep-07 4:22
Andre Oliveira13-Sep-07 4:22 
AnswerRe: Can this be used in an MFC app? Pin
Mina W Alphonce31-Oct-07 14:31
Mina W Alphonce31-Oct-07 14:31 
QuestionCan this be used in an ASP.net app? Pin
dragon4125-Jul-07 18:48
dragon4125-Jul-07 18:48 
GeneralNeed a working timeout event with a socket Pin
Bo Hansen13-Jul-07 1:34
Bo Hansen13-Jul-07 1:34 
GeneralRe: Need a working timeout event with a socket Pin
Bo Hansen16-Jul-07 22:51
Bo Hansen16-Jul-07 22:51 
QuestionRe: Need a working timeout event with a socket Pin
flaminidavid5-Jun-08 2:55
flaminidavid5-Jun-08 2:55 
GeneralConnection via internet or LAN Pin
peterkoNovak25-Feb-07 4:11
peterkoNovak25-Feb-07 4:11 
QuestionCan't send raw bytes? Pin
DARKGuy29-Oct-06 7:25
DARKGuy29-Oct-06 7:25 
Generalinternet connection [modified] Pin
dark_magician_628-Oct-06 1:22
dark_magician_628-Oct-06 1:22 
GeneralVS2005 Fixes Pin
Charles Van Lingen25-Jul-06 10:05
Charles Van Lingen25-Jul-06 10:05 
QuestionHow to Disconnect??? Pin
psycik15-Jul-06 21:27
psycik15-Jul-06 21:27 
AnswerRe: How to Disconnect??? Pin
What Code20-Jul-06 15:15
What Code20-Jul-06 15:15 
GeneralError when connecting (VS2005) Pin
micsaund1-Jul-06 17:38
micsaund1-Jul-06 17:38 
GeneralRe: Error when connecting (VS2005) Pin
Mina W Alphonce4-Jul-06 1:57
Mina W Alphonce4-Jul-06 1:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.