欢迎光临

木子屋

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

作者: dnawo

日期: 2011-09-16 09:23 AM

分类: Win编程

内容: 一、示例代码
1.服务器端代码
复制内容到剪贴板 程序代码using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Server(10086); //监听10086端口
}
/// <summary>
/// 服务器端
/// </summary>
/// <param name="port"></param>
static void Server(int port)
{
try
{
//1.监听端口
TcpListener server = new TcpListener(IPAddress.Any, port);
server.Start();
Console.WriteLine("{0:HH:mm:ss}->监听端口{1}...", DateTime.Now, port);
//2.等待请求
while (true)
{
try
{
//2.1 收到请求
TcpClient client = server.AcceptTcpClient(); //停在这等待连接请求
IPEndPoint ipendpoint = client.Client.RemoteEndPoint as IPEndPoint;
NetworkStream stream = client.GetStream();
//2.2 解析数据,长度<1024字节
string data = string.Empty;
byte[] bytes = new byte[1024];
int length = stream.Read(bytes, 0, bytes.Length);
if (length > 0)
{
data = Encoding.Default.GetString(bytes, 0, length);
Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2})：{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
}
//2.3 返回状态
byte[] messages = Encoding.Default.GetBytes("ok.");
stream.Write(messages, 0, messages.Length);
//2.4 关闭客户端
stream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
}
}
}
catch (SocketException socketEx)
{
//10013 The requested address is a broadcast address, but flag is not set.
if (socketEx.ErrorCode == 10013)
Console.WriteLine("{0:HH:mm:ss}->启动失败,请检查{1}端口有无其他程序占用.", DateTime.Now, port);
else
Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, socketEx.Message);
}
catch (Exception ex)
{
Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
}
Console.ReadKey();
}
}
}
2.客户端代码
复制内容到剪贴板 程序代码using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Client("192.168.1.100", 10086, "mzwu.com"); //发送数据
}
/// <summary>
/// 客户端
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="message"></param>
static void Client(string ip, int port, string message)
{
try
{
//1.发送数据
TcpClient client = new TcpClient(ip, port);
IPEndPoint ipendpoint = client.Client.RemoteEndPoint as IPEndPoint;
NetworkStream stream = client.GetStream();
byte[] messages = Encoding.Default.GetBytes(message);
stream.Write(messages, 0, messages.Length);
Console.WriteLine("{0:HH:mm:ss}->发送数据(to {1})：{2}", DateTime.Now, ip, message);
//2.接收状态,长度<1024字节
byte[] bytes = new Byte[1024];
string data = string.Empty;
int length = stream.Read(bytes, 0, bytes.Length);
if (length > 0)
{
data = Encoding.Default.GetString(bytes, 0, length);
Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2})：{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
}
//3.关闭对象
stream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
}
Console.ReadKey();
}
}
}
二、SocketException.ErrorCode代码列表
引用内容10004 The operation is canceled.
10013 The requested address is a broadcast address, but flag is not set.
10014 Invalid argument.
10022 Socket not bound, invalid address or listen is not invoked prior to accept.
10024 No more file descriptors are available, accept queue is empty.
10035 Socket is non-blocking and the specified operation will block.
10036 A blocking Winsock operation is in progress.
10037 The operation is completed. No blocking operation is in progress.
10038 The descriptor is not a socket.
10039 Destination address is required.
10040 The datagram is too large to fit into the buffer and is truncated.
10041 The specified port is the wrong type for this socket.
10042 Option unknown, or unsupported.
10043 The specified port is not supported.
10044 Socket type not supported in this address family.
10045 Socket is not a type that supports connection oriented service.
10047 Address Family is not supported.
10048 Address in use.
10049 Address is not available from the local machine.
10050 Network subsystem failed.
10051 The network cannot be reached from this host at this time.
10052 Connection has timed out when SO_KEEPALIVE is set.
10053 Connection is aborted due to timeout or other failure.
10054 The connection is reset by remote side.
10055 No buffer space is available.
10056 Socket is already connected.
10057 Socket is not connected.
10058 Socket has been shut down.
10060 The attempt to connect timed out.
10061 Connection is forcefully rejected.
10201 Socket already created for this object.
10202 Socket has not been created for this object.
11001 Authoritative answer: Host not found.
11002 Non-Authoritative answer: Host not found.
11003 Non-recoverable errors.
11004 Valid name, no data record of requested type.
三、参考资料
@.TcpListener 类：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcplistener(v=VS.80).aspx
@.TcpClient 类：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcpclient(v=VS.80).aspx

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

登录

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

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.895 ms

返回

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

你没有权限发表评论

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

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.895 ms

返回

暂无评论

返回

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

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.926 ms

返回