Socket编程-UDP和TCP协议的区别
Socket编程-TCP服务器端+客户端 TCP服务器端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 using System;using System.Text;using System.Net.Sockets;using System.Net;namespace SocketNetLearning1 { class Program { static void Main (string [] args ) { Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true ); IPAddress ipaddress = new IPAddress(new byte [] { 192 , 168 , 0 , 169 }); EndPoint point = new IPEndPoint(ipaddress, 7788 ); tcpServer.Bind(point); tcpServer.Listen(100 ); Console.WriteLine("开始监听" ); Socket clientSocket = tcpServer.Accept(); Console.WriteLine("一个客户端连接过来了" ); string message = "Hello 欢迎你" ; byte [] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); Console.WriteLine("向客户端发送了欢迎消息" ); byte [] data2 = new byte [1024 ]; int length = clientSocket.Receive(data2); string message2 = Encoding.UTF8.GetString(data2,0 ,length); Console.WriteLine(string .Format("接收到的消息:{0}" , message2)); Console.ReadKey(); } } }
TCP客户端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 using System;using System.Text;using System.Net;using System.Net.Sockets;namespace SocketNetTcpClient { class TcpClient { static void Main (string [] args ) { Socket tcpClinet = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipaddress = IPAddress.Parse("192.168.0.169" ); EndPoint point = new IPEndPoint(ipaddress, 7788 ); tcpClinet.Connect(point); byte [] data = new byte [1024 ]; int length = tcpClinet.Receive(data); string message = Encoding.UTF8.GetString(data, 0 , length); Console.WriteLine(message); string message2 = Console.ReadLine(); tcpClinet.Send(Encoding.UTF8.GetBytes(message2)); Console.ReadKey(); } } }
运行效果
聊天室案例 TCP服务器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 using System;using System.Collections.Generic;using System.Net.Sockets;using System.Net;namespace SocketNetLearning1 { class TcpServer { static List<Client> clientList = new List<Client>(); public static void BroadcastMessage (string message ) { var notConnectedList = new List<Client>(); foreach (var client in clientList) { if (client.Connected) client.SendMessage(message); else notConnectedList.Add(client); } foreach (var temp in notConnectedList) { clientList.Remove(temp); } } static void Main (string [] args ) { Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.169" ), 7788 )); tcpServer.Listen(100 ); Console.WriteLine("服务器已开启" ); while (true ) { Socket clientSocket = tcpServer.Accept(); Console.WriteLine("一个用户已连接!" ); Client client = new Client(clientSocket); clientList.Add(client); } Console.ReadKey(); } } }
Client类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 using System;using System.Net.Sockets;using System.Text;using System.Threading;namespace SocketNetLearning1 { class Client { private Socket clientSocket; private Thread t; private readonly byte [] data = new byte [1024 ]; public Client (Socket s ) { clientSocket = s; t = new Thread(ReceiveMessage); t.Start(); } private void ReceiveMessage () { while (true ) { if (clientSocket.Poll(10 , SelectMode.SelectRead)) { clientSocket.Close(); break ; } int length = clientSocket.Receive(data); string message = Encoding.UTF8.GetString(data, 0 , length); TcpServer.BroadcastMessage(message); Console.WriteLine("收到了消息:" + message); } } public void SendMessage (string message ) { byte [] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); } public bool Connected { get { return clientSocket.Connected; } } } }
Unity客户端 客户端可输入IP地址,端口号,昵称;获取消息添加了本地的时间节点以及富文本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using UnityEngine;using UnityEngine.UI;public class TCPClientScript : MonoBehaviour { public InputField nameInputField; public InputField ipAddressInputField; public InputField portInputField; public InputField messageInputField; public Text textValue; Socket clientSocket; Thread t; readonly byte [] data = new byte [1024 ]; string message = "" ; void Update () { if (message != null && message != "" ) { string [] messages = message.Split(',' ); textValue.text += "\n" + "<color=red>" + messages[0 ] + "\t" + GetTime() + "</color>" + "\n" + "\t" + messages[1 ]; message = "" ; } } public void OnConnectedToServer () { string ipAdress = ipAddressInputField.text; int port = Convert.ToInt32(portInputField.text); clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAdress), port)); t = new Thread(ReceiveMessage); t.Start(); } void ReceiveMessage () { while (true ) { if (clientSocket.Connected == false ) break ; int length = clientSocket.Receive(data); message = Encoding.UTF8.GetString(data, 0 , length); } } void SendAMessage (string message ) { byte [] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); } public void OnSendButtonClick () { string value = nameInputField.text + "," + messageInputField.text; SendAMessage(value ); messageInputField.text = "" ; } private void OnDestroy () { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } public string GetTime () { System.DateTime currentTime = new DateTime(); currentTime = System.DateTime.Now; string timeStr = currentTime.Year.ToString() + "/" + currentTime.Month.ToString() + "/" + currentTime.Day.ToString() + " " + currentTime.Hour.ToString() + ":" + currentTime.Minute.ToString() + ":" + currentTime.Second.ToString() + " " ; return timeStr; } }
Socket编程-UDP服务器端与客户端 UDP服务器端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace UDPLearning { class UdpServer { private static Socket udpServer; static void Main (string [] args ) { udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.169" ), 7788 )); new Thread(ReceiveMessage) { IsBackground = true }.Start(); Console.ReadKey(); } static void ReceiveMessage () { while (true ) { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0 ); byte [] data = new byte [1024 ]; int length = udpServer.ReceiveFrom(data, ref remoteEndPoint); string message = Encoding.UTF8.GetString(data, 0 , length); Console.WriteLine("从IP:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message); } } } }
UDP客户端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System;using System.Net;using System.Net.Sockets;using System.Text;namespace UDPLearningClient { class UdpClient { static void Main (string [] args ) { Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); while (true ) { EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.0.169" ), 7788 ); string message = Console.ReadLine(); byte [] data = Encoding.UTF8.GetBytes(message); udpClient.SendTo(data, serverPoint); } } } }
TcpListener与TcpcLient socket - 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
方法接收传入的数据文报
TcpClient
TcpClient
类提供了一些简单的方法,用于在同步阻止模式下 通过网络来连接、发送和接收流数据。为使TcpClient
连接并交换数据,使用TCP Protocoltype创建的TcpListener
或Socket必须侦听是否有传入的连接请求。可以使用下面两种方法之一连接到该侦听器:
创建一个TcpClient
,并调用三个可用的Connect
方法之一。
使用远程主机的主机名和端口号创建TcpClient
。此构造函数将自动尝试一个连接。
给继承者的说明要发送和接收的数据,请使用GetStream
方法来获取一个NetworkStream
。调用NetworkStream
的Write
和Read
方法与远程主机之间发送和接收数据。使用Close
方法释放与TcpClient关联的所有资源。
TcpListener
TcpListener
类提供一些简单方法,用于在阻止同步模式 下侦听和接受传入连接请求。可使用TcpClient
或Socket来连接TcpListener
。可使用IPEndPoint
、本地IP地址以及端口号或者仅使用端口号,来创建TcpListener
。可以将本地IP地址指定为Any,将本地端口号指定为0(如果希望基础服务提供程序为您分配这些值)。如果您选择这样做,可以在套接字后使用LocalEndPoint
属性来标记已指定的信息。
Start
方法用来开始侦听传入的连接请求。Start将对传入连接进行排队,直至您调用Stop
方法或它已经完成MaxConnections
排队为止。可使用AcceptSocket
或AcceptTcpClient
从传入连接请求队列提取连接。这两种方法将阻止。如果要避免阻止,可首先使用Pending
方法来确定队列中是否有可用的连接请求。
调用Stop
方法来关闭TcpListener
。
TcpListener服务器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 using System;using System.Net;using System.Net.Sockets;using System.Text;namespace TcplistenerLearning { class TcpListenerProgram { static void Main (string [] args ) { TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.169" ), 7788 ); listener.Start(); TcpClient client = listener.AcceptTcpClient(); NetworkStream stream = client.GetStream(); byte [] data = new byte [1024 ]; while (true ) { int length = stream.Read(data, 0 , 1024 ); string message = Encoding.UTF8.GetString(data, 0 , length); Console.WriteLine("收到了消息" + message); } } } }
TcpClient客户端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 using System;using System.Net.Sockets;using System.Text;namespace TcpClientLearning { class TcpClientProgram { static void Main (string [] args ) { TcpClient client = new TcpClient("192.168.0.169" , 7788 ); NetworkStream stream = client.GetStream(); while (true ) { string message = Console.ReadLine(); byte [] data = Encoding.UTF8.GetBytes(message); stream.Write(data, 0 , data.Length); } } } }
UdpClient UDP协议不需要做连接,客户端是服务器端,服务器端也是客户端
UdpClient
类提供了一些简单的方法,用于在阻止同步模式 下发送和接收无连接UDP数据报。因为UDP是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一类建立默认远程主机:
使用远程主机名和端口号作为参数创建UdpClient
类的实例。
创建UdpClient
类的实例,然后调用Connect
方法。
可以使用在UdpClient
中提供的任何一种发送方法将数据发送到远程设备。使用Receive
方法可以从远程主机接收数据。
UdpClient
方法还允许发送和接收多路广播数据报。使用JoinMulticastGroup
方法可以将UdpClient
预订给多路广播组。使用DropMulticastGroup
方法可以从多路广播组中取消对UdpClient
的预订。
Udp服务器端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 using System;using System.Net;using System.Net.Sockets;using System.Text;namespace UdpClientApp1 { class UdpClientServer { static void Main (string [] args ) { UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.0.169" ), 7788 )); while (true ) { IPEndPoint point = new IPEndPoint(IPAddress.Any, 0 ); byte [] data = udpClient.Receive(ref point); string message = Encoding.UTF8.GetString(data); Console.WriteLine("收到了消息" + message); } } } }
Udp客户端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System;using System.Net;using System.Net.Sockets;using System.Text;namespace UdpClientApp2 { class UdpClientClient { static void Main (string [] args ) { UdpClient client = new UdpClient(); UTF8Encoding uTF8Encoding = new UTF8Encoding(); while (true ) { string message = Console.ReadLine(); byte [] data = uTF8Encoding.GetBytes(message); client.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.168.0.169" ), 7788 )); } } } }