欢迎光临

木子屋

标题: C#使用Socket发送和接收TCP数据示例

作者: dnawo

日期: 2014-08-15 02:09 PM

分类: Win编程

内容: 复制内容到剪贴板 程序代码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>
/// 监听请求
/// </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, 1000); //1 seconds timeout.
Console.WriteLine("Receive：" + receiveData);
Send(acceptSocket, "ok");
DestroySocket(acceptSocket); //import
}
}
/// <summary>
/// 发送数据
/// </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);
Send(clientSocket, data);
result = Receive(clientSocket, 1000 * 2); //1*2 seconds timeout.
DestroySocket(clientSocket);
//Console.WriteLine("Send：{0}\r\nReceive：{1}", data, result);
return result;
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="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>
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 //timeout Exception
{
//心得：
//1.若缓冲区buffer比接收数据小，需多次Receive才能完成；
//2.多次Receive时，每次接收字节数length大小不固定；
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>
/// 销毁Socket对象
/// </summary>
/// <param name="socket"></param>
private static void DestroySocket(Socket socket)
{
if (socket != null)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
}
socket.Close();
}
}
}
}
重要说明：Receive通常是双方约定一个结束符，或者发送方发送完毕立即关闭Socket，否则只能通过ReceiveTimeout来结束Receive(不一定可靠)。
运行服务器监听数据：
复制内容到剪贴板 程序代码SocketTest.Listen(8888);
发送和接收TCP数据：
复制内容到剪贴板 程序代码string data = "mzwu.com";
string result = SocketTest.Send("127.0.0.1", 8888, data);
Console.WriteLine("Send：{0}\r\nReceive：{1}", data, result);
Receive接收字节数测试
复制内容到剪贴板 程序代码byte[] buffer = new byte[1024];
int length = socket.Receive(buffer);
Console.WriteLine("Receive length: " + length);
while (length > 0)
{
//todo

length = socket.Receive(buffer);
Console.WriteLine("Receive length: " + length);
}
运行结果：
引用内容Receive length: 1024
Receive length: 1024
Receive length: 832
Receive length: 1024
Receive length: 1024
Receive length: 832
Receive length: 1024
Receive length: 416
Receive length: 1024
Receive length: 1024
Receive length: 1024
Receive length: 229
Receive length: 0
参考资料
[1].Socket 类：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket(v=vs.80).aspx
[2].Socket 方法：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket_methods(v=vs.80).aspx

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.975 ms

返回

标题: C#使用Socket发送和接收TCP数据示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.975 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.021 ms

返回