Socket和NetworkStream的区别:
在C#中,Socket和NetworkStream是用于进行网络通信的两种不同的API,Socket提供了更底层且灵活的网络通信功能,适用于对网络传输细节有较高要求的场景。而NetworkStream则是基于Socket的高级封装,提供了简化的读写接口,适用于大多数常见的网络通信任务。
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 IPEndPoi