public class Testconnect
{
String hostip = "";
int port = 3314;
public string recmsg = "";
Socket socketc = null;
Private readonly ManualResetEvent timeoutobject = new ManualResetEvent (false);
Public Testconnect (string hostip, int port)
{
This.hostip = HostIP;
This.port = port;
}
public bool Connect ()
{
Create an endpoint (EndPoint)
IPAddress IP = ipaddress.parse (hostip);//Convert IP address string to an instance of the IPAddress type
IPEndPoint ipe = new IPEndPoint (IP, port);//Initializes a new instance of the IPEndPoint class with the specified port and IP
Create socket
SOCKETC = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//Create a socket pair image, if using the UDP protocol, You want to use a socket of type Sockettype.dgram
Try
{
Return Connect (ipe,3000);
}
catch (SocketException ex)
{
Socketc.close ();
SOCKETC = null;
return false;
}
}
<summary>
Socket connection Request
</summary>
<param name= "Remoteendpoint" > Network Endpoints </param>
<param name= "Timeoutmsec" > Time Out </param>
public bool Connect (ipendpoint remoteendpoint, int timeoutmsec)
{
Timeoutobject.reset ();
Socketc = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
Socketc.beginconnect (Remoteendpoint, Callbackmethod, socketc);
Block Current thread
if (Timeoutobject.waitone (Timeoutmsec, False))
{
return true;
}
Else
{
return false;
}
}
--Async callback method
private void Callbackmethod (IAsyncResult asyncresult)
{
Make the blocked thread continue
Socket socket = asyncresult. AsyncState as Socket;
if (socket. Connected)
{
Socket. EndConnect (asyncresult);
}
Timeoutobject.set ();
}
public void Testonline (String msg)
{
Socketc.send (encoding.getencoding ("gb2312"). GetBytes (msg));
Try
{
Create a communication thread
Parameterizedthreadstart pts = new Parameterizedthreadstart (serverrecmsg);
Thread thr = new Thread (pts);
Thr. IsBackground = true;
Start thread
Thr. Start (SOCKETC);
}
Catch
{throw;}
}
<summary>
Receiving information from the client
</summary>
<param name= "Socketclientpara" > Client socket Object </param>
private void Serverrecmsg (object Socketclientpara)
{
Socket socketserver = Socketclientpara as socket;
byte[] arrserverrecmsg = new byte[100];
int Len;
while (len = socketserver.receive (arrserverrecmsg))! = 0)
{
Converts a machine-accepted byte array into a string that can be read by a human
Recmsg = Encoding.Default.GetString (arrserverrecmsg, 0, Len);
if (recmsg = = "Online")
{
Break
}
}
}
}
Socket test if remote address can connect and set timeout for connection (RPM)