|
Using System;
Using System.Collections.Generic;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Namespace ConsoleApplication1
{
public static Class Sockettest
{
private static Encoding encode = Encoding.default;
///<summary>
/ Listen for requests
///</summary>
///<param name= "Port" ></PARAM>
Public static void Listen (int port)
{
Socket listensocket = new socket (AddressFamily.InterNetwork, SocketType.Stream, PROTOCOLTYPE.TCP);
Listensocket.bind (New IPEndPoint ( Ipaddress.any, port));
Listensocket.listen (100);
Console.WriteLine ("Listen" + Port + "...");
while (true)
{
Socket acceptsocket = listensocket.accept ();
String Receivedata = Receive (AcceptSocket, 5000); 5 Seconds timeout.
Console.WriteLine ("Receive:" + receivedata);
Acceptsocket.send (encode. GetBytes ("OK"));
Destroysocket ( AcceptSocket); Import
}
}
///<summary>
/ Send data
///</summary>
///<param name= "host" ></PARAM>
///< Param name= "Port" ></param>
///<param name= "Data" > </param>
///<returns></returns>
public static string Send (string host, int port, string data)
{
string result = String. Empty;
Socket clientsocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Clientsocket.connect (host, Port);
Clientsocket.send (encode. GetBytes (data));
Console.WriteLine ("Send:" + data);
result = Receive (Clientsocket, 5000 * 2); 5*2 seconds timeout.
Console.WriteLine ("Receive:" + result);
Destroysocket (Clientsocket);
return result;
}
<summary>
Receive data
</summary>
<param name= "Socket" ></param>
<param name= "Timeout" ></param>
<returns></returns>
private static string Receive (socket socket, int timeout)
{
string result = String. Empty;
Socket. ReceiveTimeout = timeout;
list<byte> data = new list<byte> ();
byte[] buffer = new byte[1024];
int length = 0;
Try
{
while (length = socket. Receive (buffer)) > 0)
{
for (int j = 0; J < length; J + +)
{
Data. ADD (Buffer[j]);
}
if (length < buffer. Length)
{
Break
}
}
}
Catch {}
if (data. Count > 0)
{
result = encode. GetString (data. ToArray (), 0, data. Count);
}
return result;
}
///<summary>
/ Destroy the Socket object
///</summary>
///<param name= "socket" ></PARAM>
private static void Destroysocket (socket socket)
{
if (socket. Connected)
{
socket. Shutdown (Socketshutdown.both);
}
socket. Close ();
}
}
}
|