基于Tcp协议的Socket
类似于B/S架构,面向连接,但不同的是服务器端可以向客户端主动推送消息。
使用Tcp协议通讯需要具备以下几个条件:
(1).建立一个套接字(Socket)
(2).绑定服务器端IP地址及端口号–服务器端
(3).利用Listen()方法开启监听–服务器端
(4).利用Accept()方法尝试与客户端建立一个连接–服务器端
(5).利用Connect()方法与服务器建立连接–客户端
(5).利用Send()方法向建立连接的主机发送消息
(6).利用Recive()方法接受来自建立连接的主机的消息(可靠连接)
TcpServer
public static void TcpServer(IPEndPoint serverIP)
{
Console.WriteLine("客户端Tcp连接模式");
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpServer.Bind(serverIP);
tcpServer.Listen(100);
Console.WriteLine("开启监听...");
new Thread(() =>
{
while (true)
{
try
{
TcpRecive(tcpServer.Accept());
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
break;
}
}
}).Start();
Console.WriteLine("\n\n输入\"Q\"键退出。");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
tcpServer.Close();
}
TcpRecive
public static void TcpRecive(Socket tcpClient)
{
new Thread(() =>
{
while (true)
{
byte[] data = new byte[1024];
try
{
int length = tcpClient.Receive(data);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
break;
}
Console.WriteLine(string.Format("收到消息:{0}", Encoding.UTF8.GetString(data)));
string sendMsg = "收到消息!";
tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg));
}
}).Start();
}
TcpClient
public static void TcpServer(IPEndPoint serverIP)
{
Console.WriteLine("客户端Tcp连接模式");
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
tcpClient.Connect(serverIP);
}
catch (SocketException e)
{
Console.WriteLine(string.Format("连接出错:{0}", e.Message));
Console.WriteLine("点击任何键退出!");
Console.ReadKey();
return;
}
Console.WriteLine("客户端:client-->server");
string message = "我上线了...";
tcpClient.Send(Encoding.UTF8.GetBytes(message));
Console.WriteLine(string.Format("发送消息:{0}", message));
new Thread(() =>
{
while (true)
{
byte[] data = new byte[1024];
try
{
int length = tcpClient.Receive(data);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
break;
}
Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
}
}).Start();
Console.WriteLine("\n\n输入\"Q\"键退出。");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
tcpClient.Close();
}
基于Udp协议的Socket
基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)
(1).建立一个套接字(Socket)
(2).绑定服务器端IP地址及端口号–服务器端
(3).通过SendTo()方法向指定主机发送消息
(需提供主机IP地址及端口)
(4).通过ReciveFrom()方法接收指定主机发送的消息
(需提供主机IP地址及端口)
UdpServer
public static void UdpServer(IPEndPoint serverIP)
{
Console.WriteLine("客户端Udp模式");
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpServer.Bind(serverIP);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)ipep;
new Thread(() =>
{
while (true)
{
byte[] data = new byte[1024];
try
{
int length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
break;
}
Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
string sendMsg = "收到消息!";
udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None, Remote);
}
}).Start();
Console.WriteLine("\n\n输入\"Q\"键退出。");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
udpServer.Close();
}
UdpClient
public static void UdpClient(IPEndPoint serverIP)
{
Console.WriteLine("客户端Udp模式");
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string message = "我上线了...";
udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP);
Console.WriteLine(string.Format("发送消息:{0}", message));
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
new Thread(() =>
{
while (true)
{
byte[] data = new byte[1024];
try
{
int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
break;
}
Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
}
}).Start();
Console.WriteLine("\n\n输入\"Q\"键退出。");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
udpClient.Close();
}
TCP和UDP的区别
TCP协议和UDP协议连接过程的区别
1.基于连接与无连接;
2.对系统资源的要求(TCP较多,UDP少);
3.UDP程序结构较简单;
4.流模式与数据报模式 ;
5.TCP保证数据正确性,UDP可能丢包,TCP保证数据顺序,UDP不保证。
TCPClient、TCPListener 和 UDPClient 类
应用程序可以通过 TCPClient、TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务。这些协议类建立在 System.Net.Sockets.Socket 类的基础之上,负责数据传送的细节。(也就是说TCPClient、TCPListener 和 UDPClient 类是用来简化Socket)
TcpClient 和 TcpListener 使用 NetworkStream 类表示网络。使用 GetStream 方法返回网络流,然后调用该流的 Read 和 Write 方法。NetworkStream 不拥有协议类的基础套接字,因此关闭它并不影响套接字。
UdpClient 类使用字节数组保存 UDP 数据文报。使用 Send 方法向网络发送数据,使用 Receive 方法接收传入的数据文报。
TcpListener
static void Main(string[] args)
{
//1、TcpListener对Socket进行了一层封装,这个类里面自己会去创建Socket对象
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.1.117"), 6688);
//2、开始进行监听
listener.Start();
//3、等待客户端连接进来
TcpClient client = listener.AcceptTcpClient();
//4、取得客户端发送过来的数据
//得到一个网络流,从这个网络流可以取得客户端发送过来的数据
NetworkStream stream = client.GetStream();
byte[] data = new byte[1024]; //创建一个数据容器
//返回实际读取的字节长度
int length = stream.Read(data, 0, 1024); //读取数据
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("收到了消息:" + message) ;
//5、释放资源
stream.Close();
client.Close();
listener.Stop(); //停止监听
Console.ReadKey();
}
TcpClient
static void Main(string[] args)
{
//当我们创建TcpClient对象的时候,就会跟Server去建立连接
TcpClient client=new TcpClient("192.168.1.117", 6688);
//通过网络流进行数据的交换
NetworkStream stream = client.GetStream();
//read用来读取数据,write用来写入数据(其实就是发送数据)
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data,0,data.Length);
stream.Close();
client.Close();
Console.ReadKey();
}