Senin, 20 Mei 2013
Simple Socket Control(s) to Create Server-Client Applications
Do you like this story?
Introduction
This simple project can be used instead ofTcpClient, 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 ofTcpClient 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.ConnectFunction used to connect to a remote endpoint.
Hoststring, specifies the IP, it can be (e.g. "127.0.0.1") or (e.g. "www.codeproject.com").
portint, specifies the port in the remote endpoint that there is a socket listening to it.
ModeOne of theConnectionModeenum, it is recommended to useSyncConnectAsyncRecv, other options can also be used.
BindThis 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.
SendSend the array of bytes to the remote endpoint, use this function for a connected socket only.
ReceiveThis function is used inBlockingmode, 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.)
Lengthint, the maximum length of the array that can be passed to the buffer. If the received data is greater than theLength, then the returned array will contain only the data of sizeLength, you must callReceiveagain to receive the other data. If the received data is less than theLength, then the returned array will be of the size of the data received.
CloseUse this function to close any created socket, for every created socket you must callclose socketto close the socket.
ShutdownUse this function to disablesendorreceiveor both, the param is documented in the MSDN.
recieveevent Fired when there is data available to be received, theRecieveEventArgcontains the data and the data length that is received, don't callRecievein therecieveevent, it will receive the next available data.
createevent Fired when the socket is created.
connectevent Fired in nonBlockingmode (orAsyncConnectionxxxxxxxxx) when the connection is accepted by the remote endpoint.
shutdownevent Fired when calling the shutdown function.
sendevent Fired after the send process ends.
closeevent Fired if theclosefunction is called or if the remote endpoint closes the connection or if there is any socket exception received.CloseEventArgscontains the exception and astringthat specifies the error. You can use it in a message box.
ListenSocket Class
Use this call, instead of theTcpListen class. You can start listen, stop listen and accept connection from a remote end point.PortUse it to set the port to listen to. You must set it before calling start listen.
StartListenSet the state of the socket toListeningstate.
IsBlockedIftrue, theacceptevent will not be fired when there is a request for connection, you must call theAcceptfunction. Iffalse, then theacceptevent fires.
StopListenStop listening.
closeUse this function to close any created socket, for every socket created, you must callclose socketto close the socket.
AcceptUse this function if you passtruetoStartListen. This function will block the thread, until a remote endpoint request connection is made.
createevent Fired after creating the socket.
closeevent Fired if theclosefunction is called or if the remote endpoint closes the connection or if there is any socket exception received.CloseEventArgscontains the exception and astringthat specifies the error. You can use it in a message box.
acceptevent Fired when a connection is accepted from the remote endpoint. TheAcceptEventArgscontains a connected socket that is used to create a connection.
Example
- Create a new Windows application project, named
SimpleServer. - Right click on the Toolbox - add/remove item.
- Click Browse - select sockets.dll (download it from this article).
- Click OK.
- The two classes
ConnectSocket,ListenSocketare now in the Toolbox.
IsBlocked of the connect socket to false. Add a button, name it Listen, and handle the Click event: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: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: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: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: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: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: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)

This post was written by: Brenley Mars
Brenley is a professional blogger, web designer and front end web developer. Follow him on Twitter
Langganan:
Posting Komentar (Atom)

2 Responses to “Simple Socket Control(s) to Create Server-Client Applications”
20 Mei 2013 pukul 02.08
Sorry Kalau Berantakan..
@Maars_ID :D
21 Mei 2013 pukul 02.20
wah, keren artikelnya gan
bermanfaat banget.
Jangan lupa komen backnya di http://adeputra-pkp.blogspot.com
Posting Komentar