写一个Csharp的TCP IP 例子
时间: 2023-03-14 18:27:12 浏览: 67
首先,使用C#创建一个TCP / IP服务器: using System;
using System.Net;
using System.Net.Sockets;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
// 监听任意IP地址和端口号
IPAddress ipAdr = IPAddress.Any;
int port = 13000;
IPEndPoint ipEp = new IPEndPoint(ipAdr, port);
// 创建监听套接字
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
s.Bind(ipEp);
s.Listen(10); // 开始监听
while (true)
{
Console.WriteLine("等待连接。。。");
Socket clientSock = s.Accept(); // 接受客户端连接
byte[] buffer = new byte[1024];
int byteRec = clientSock.Receive(buffer); // 接收数据
string dataRec = Encoding.ASCII.GetString(buffer, 0, byteRec);
Console.WriteLine("客户端:{0}", dataRec); // 显示接收到的数据
string dataSend = "你好!"; // 准备发送的数据
byte[] bufferSend = Encoding.ASCII.GetBytes(dataSend);
clientSock.Send(bufferSend); // 发送数据
clientSock.Close();
}
}
}
}