Ask how to improve the robustness of the socket Client in C,

Source: Internet
Author: User

Ask how to improve the robustness of the socket Client in C,

I am a newbie to Socket. I recently developed a Socket Client program. When I connect to the Server, if the server exists and the connection is allowed, the program runs normally. However, if the Server does not exist, or, if the connection is denied, the program gets stuck and no error is prompted. At first, I thought there was no Catch exception, but I checked the program and caught all the exceptions. The program was still stuck.

Please correct me! Thank you. The following is my code for this module!

Using System;
Using System. Collections;
Using System. ComponentModel;
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;
Using System. Text;


Namespace Test Program
{
/// <Summary>
/// Summary of ClassClient.
/// </Summary>
Public class ClassClient
{
// Method
Public ClassClient ()
{
//
// TODO: add the constructor logic here
//
}

// Function

# Region socket communication machine connection Function
/// <Summary>
/// Socket communication machine connection Function
/// </Summary>
/// <Param name = "remoteEP"> Remote Terminal </param>
/// <Param name = "client"> Create a client </param>
Public byte SocketConnect (EndPoint RemoteEP, Socket Client)
{
// Call the system connection Function
Client. BeginConnect (RemoteEP, new AsyncCallback (ConnectCallback), Client );

ConnectDone. WaitOne ();

Return (1 );


}
# Endregion

# Region socket connection return Function
/// <Summary>
/// Socket connection return Function
/// </Summary>
/// <Param name = "ar"> indicates the asynchronous operation status </param>
Private static void ConnectCallback (IAsyncResult ar)
{
Try
{
// Obtain the socket connection instance
Socket client = (Socket) ar. AsyncState;

// Complete the connection process.
Client. EndConnect (ar );

// Set the mark of connection completion
ConnectDone. Set ();

// Obtain the connection success message.
ConnectInfo = "connection successful! ";
}
Catch (Exception e)
{
// Get the connection failure information
ConnectInfo = e. ToString ();

// End the connection
ConnectDone. Reset ();
}
}
# Endregion

# Region socket communication host shutdown Function
/// <Summary>
/// Socket communication machine shutdown Function
/// </Summary>
/// <Param name = "Client"> socket communication instance to be closed </param>
Public byte SocketClose (Socket Client)
{
Try
{
If (Client! = Null)
{
// Disable it if communication information is still generated
If (Client. Connected)
{
Client. Shutdown (SocketShutdown. Both );
}
// Disable socket communication
Client. Close ();

// Get the closing success message
CloseInfo = "the communication host is closed! ";
}
Return (1 );
}
Catch (Exception e)
{
// Obtain the message indicating that the communication is disabled.
CloseInfo = e. ToString ();

Return (0 );
}
}
# Endregion

# Region data sending Function
/// <Summary>
/// Data sending Function
/// </Summary>
/// <Param name = "Client"> connected socket communication machine instance (Client) </param>
/// <Param name = "MessageSend"> information to be sent </param>
/// <Returns>
/// Returns whether the message is sent successfully.
/// </Returns>
Public bool SocketSend (Socket Client, String MessageSend)
{
// Convert the data into Byte ASCII code.
Byte [] ByteData = Encoding. ASCII. GetBytes (MessageSend );

// Send data to a remote device (Server.
Client. BeginSend (ByteData, 0, ByteData. Length, SocketFlags. None, new AsyncCallback (SendCallback), Client );

// Send flag event wait
SendDone. WaitOne ();

// Returns true
Return (true );
}
# Endregion

# Region data sending return Function
/// <Summary>
/// Data sending return Function
/// </Summary>
/// <Param name = "ar"> indicates the asynchronous operation status </param>
Private static void SendCallback (IAsyncResult ar)
{
Try
{
// Obtain the socket connection instance
Socket Client = (Socket) ar. AsyncState;

// Data is sent to the remote device
Int bytesSent = Client. EndSend (ar );

// Set the flag for sending completion
SendDone. Set ();

// Obtain the sending completion Information
SendInfo = "sending completed! ";

}
Catch (Exception e)
{
// Get the sending failure message
SendInfo = e. ToString ();

// End sending flag
SendDone. Reset ();
}
}

# Endregion

# Region data receiving function
/// <Summary>
/// Data receiving function
/// </Summary>
/// <Param name = "client"> connected socket communication machine instance (client) </param>
/// <Returns>
/// Return the received data
/// </Returns>
Public string SocketReceive (Socket Client)
{
Try
{
Int I;

// Create an instance.
StateObject State = new StateObject ();
State. WorkSocket = Client;

// Start receiving data from a remote device
Client. BeginReceive (State. Buffer, 0, StateObject. BufferSize, 0, new AsyncCallback (effececallback), State );

// Convert received byte data to a string
For (I = 0; I <State. Buffer. Length; I ++)
{
RevData + = State. Buffer [I]. ToString ();
}

// Return the received data
Return (RevData );
}
Catch (Exception e)
{
// Get receiving Failure Information
RevInfo = e. ToString ();

// Return an empty string
Return ("");
}
}
# Endregion

# Region data receiving and return functions
/// <Summary>
/// Data receiving return Function
/// </Summary>
/// <Param name = "ar"> indicates the asynchronous operation status </param>
Private static void extends ecallback (IAsyncResult ar)
{
Try
{
// Create an instance
StateObject State = (StateObject) ar. AsyncState;
Socket Client = State. WorkSocket;

// Read data from a remote device
Int BytesRead = Client. EndReceive (ar );

If (BytesRead> 0)
{
// There may be too much data, so store it slowly

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.