在C#中,Socket和NetworkStream是用于进行网络通信的两种不同的API,Socket提供了更底层且灵活的网络通信功能,适用于对网络传输细节有较高要求的场景。而NetworkStream则是基于Socket的高级封装,提供了简化的读写接口,适用于大多数常见的网络通信任务。
tcp服务端
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace ServerTcp
{
class Program
{
static void Main(string[] args)
{
//创建Socket
Socket ServerTcp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定IP和端口
IPAddress iPAddress = new IPAddress(new byte[] { 127,0,0,1 });
EndPoint endPoint = new IPEndPoint(iPAddress, 7777);
ServerTcp.Bind(endPoint);
//监听,等待客户端进行链接
Console.WriteLine("开始监听");
ServerTcp.Listen(100);//开始监听,100为最大连接数
Console.WriteLine("等待客户端链接");
Socket client = ServerTcp.Accept();//接收客户端;实际上是暂停当前线程
//向客户端发送消息
string mess1 = "服务器正在运行";
byte[] buffer = Encoding.UTF8.GetBytes(mess1);//字符串转为字节
client.Send(buffer);
while(true)
{
//接收客户端的消息
byte[] data = new byte[1024];//定义缓存区
int length = client.Receive(data);//信息的有效长度
string mess2 = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("向客户端发送的消息:" + mess2);
}
}
}
}
tcp客户端
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace ClientTcp
{
class Program
{
static void Main(string[] args)
{
//创建Socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//请求与服务器连接
IPAddress ip = IPAddress.Parse("127.0.0.1");
EndPoint endPoint = new IPEndPoint(ip,7777);
tcpClient.Connect(endPoint);
//接收消息
byte[] buffer = new byte[1024];//定义缓存区
int length = tcpClient.Receive(buffer);//将接收的数组放入缓存区,并返回字节数
string message = Encoding.UTF8.GetString(buffer, 0, length);//对缓存区中的数据进行解码成字符串
Console.WriteLine("从服务端接收的信息:"+message);
while(true)
{
//发送消息
string str = Console.ReadLine();//输入发送的信息
tcpClient.Send(Encoding.UTF8.GetBytes(str));//将string转成字节流后,发送消息
}
}
}
}
udp服务端
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UdpServer
{
class Program
{
static void Main(string[] args)
{
//创建Socket
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定ip和端口
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777);
udpServer.Bind(endPoint);
while (true)
{
//接收消息
EndPoint endPointSend = new IPEndPoint(IPAddress.Any, 0);//任意IP地址,任意端口
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref endPointSend);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("接收客户端发送的信息:" + message);
}
}
}
}
udp客户端
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace UdpClient
{
class Program
{
static void Main(string[] args)
{
//创建socket
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777);
while (true)
{
//发送消息
string message = Console.ReadLine();
udpClient.SendTo(Encoding.UTF8.GetBytes(message), endPoint);
}
}
}
}
客户端
using System;
using System.Net.Sockets;
using System.Text;
namespace Client
{
class Program
{
static void Main(string[] args)
{
//服务器IP和端口
string serverIP = "127.0.0.1";
int serverPort = 7777;
//创建TCP客户端
TcpClient client = new TcpClient();
client.Connect(serverIP, serverPort);
//获取网络流
NetworkStream stream = client.GetStream();
//发送消息给服务器
string message = "这里是客户端!!";
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine("客户端发送消息:" + message);
// 读取服务器的响应
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("客户端接收到信息:" + response);
// 关闭连接
stream.Close();
client.Close();
Console.WriteLine("客户端连接已关闭");
Console.ReadKey();
}
}
}
服务端
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server
{
class Program
{
static void Main(string[] args)
{
//定义ip和端口后开始监听
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 7777;
TcpListener listener = new TcpListener(ipAddress, port);
listener.Start();
Console.WriteLine("服务器正在运行,等待客户端连接");
//接收客户端
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("客户端已经连接");
//获取网络流
NetworkStream steam = client.GetStream();
//读取客户端发送的消息
byte[] buffer = new byte[1024];
int bytesRead = steam.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer,0,bytesRead);
Console.WriteLine("服务器接收到消息:" + message);
//发送响应给客户端
string response = "这里是服务器!!";
byte[] data = Encoding.UTF8.GetBytes(response);
steam.Write(data,0,data.Length);
Console.WriteLine("服务器发送信息:" + response);
//关闭连接
steam.Close();
client.Close();
listener.Stop();
Console.WriteLine("服务器连接关闭");
Console.ReadKey();
}
}
}
参考:
Socket 类 (System.Net.Sockets) | Microsoft Learn