Console program:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Net;
Using System.Net.Sockets;
Using ConsoleApplication1;
Namespace ConsoleApplication1
{
public static Class Sockettest
{
private static Encoding encode = Encoding.default;
<summary>
Listening 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>
Destroying the Socket object
</summary>
<param name= "Socket" ></param>
private static void Destroysocket (socket socket)
{
if (socket. Connected)
{
Socket. Shutdown (Socketshutdown.both);
}
Socket. Close ();
}
}
}
Class Program
{
static void Main (string[] args)
{
Sockettest.listen (9876);
}
}
C#PC terminal TCP/IP and Android communication source code