在发送数据之前,首发双方约定好统一的端口,数据起始符、结束符
Socket 通过单一信道进行收发数据
class Program
{
static void Main(string[] args)
{
ServerController.Listen(8888);
string data = "我真帅";
string result = ServerController.Send("127.0.0.1", 8888, data);
Console.WriteLine("Send:{0}\r\nReceive:{1}", data, result);
Console.ReadKey();
}
}
`</pre>
</div>
<div>
<div>
<pre>`public class ServerController //: Controller
{
/*数据的开始结束符号*/
/// <summary>
/// 编码 解码
/// </summary>
private static Encoding encode = Encoding.Default;
/// <summary>
/// 监听请求
/// </summary>
/// <param name="port">端口</param>
public static void Listen(int port)
{
//IPv4 双向基于连接的字节流 传输控制协议
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 将Socket与本地端点相关联
listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
// 挂起连接队列的最大长度
listenSocket.Listen(100);
Console.WriteLine("Listen " + port + " ...");
//循环监听
while (true)
{
//未接收,则一直阻塞
Socket acceptSocket = listenSocket.Accept();
try
{
//1s timeout.
string receiveData = Receive(acceptSocket, 1000);
Console.WriteLine("Receive:" + receiveData);
//发送接受状态
Send(acceptSocket, "ok");
}
catch (Exception e)
{
//发送接受状态
Send(acceptSocket, "failed");
Console.WriteLine(e);
}
DestroySocket(acceptSocket); //import
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="host">主机名 IP</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);
try
{
//建立与远程hos的连接
clientSocket.Connect(host, port);
////发送数据
//clientSocket.Send(encode.GetBytes(data));
//发送数据data
Send(clientSocket, data);
//等待2秒
result = Receive(clientSocket, 1000 * 2); //1*2 seconds timeout.
//销毁socket
}
catch (Exception e)
{
Console.WriteLine("由于目标计算机积极拒绝,无法连接" + e);
}
DestroySocket(clientSocket);
//Console.WriteLine("Send:{0}\r\nReceive:{1}", data, result);
return result;
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="socket">socket</param>
/// <param name="data">数据</param>
private static void Send(Socket socket, string data)
{
//字符编码为字节序列,然后发送
socket.Send(encode.GetBytes(data));
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="socket"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public 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];
try
{
//1.若缓冲区buffer比接收数据小,需多次Receive才能完成;
//2.多次Receive时,每次接收字节数length大小不固定;
//3.实际接收字节数据
int length = 0;
//循环接收数据到接收缓冲区
while ((length = socket.Receive(buffer)) > 0)
{
for (int j = 0; j < length; j++)
{
data.Add(buffer[j]);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (data.Count > 0)
{
//字节转化为字符
result = encode.GetString(data.ToArray(), 0, data.Count);
}
return result;
}
/// <summary>
/// 销毁Socket对象
/// </summary>
/// <param name="socket"></param>
private static void DestroySocket(Socket socket)
{
try
{
if (socket != null)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
}
socket.Close();
}
Console.WriteLine("Socket销毁成功");
}
catch (Exception e)
{
Console.WriteLine("Socket销毁失败" + e);
throw;
}
}
}
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/2b86d684(v=vs.110).aspx
https://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket_methods(v=vs.80).aspx