主要内容
- Socket编程-Udp和Tcp协议的区别
- Socket编程-Tcp服务器端
- 聊天室案例
- Socket编程-Udp服务器端与客户端
- Tcplistener与Tcpclient
- Udpclient
Socket编程-Udp和Tcp协议的区别
Tcp 会保证包的顺序,先发的先到达,后发的后到达;Udp不保证。
Socket编程-Tcp服务器端+客户端
Tcp服务器端
using
Tcp客户端
using
运行效果
先运行服务器,再运行客户端。
聊天室案例
Tcp服务器
using
Client类
using
Unity客户端
客户端可输入IP地址,端口号,昵称;获取消息添加了本地的时间节点以及富文本。
using
Socket编程-Udp服务器端与客户端
Socket编程_Udp服务器端
using
Socket编程_Udp客户端
using
Tcplistener与Tcpclient
服务器_tcplistener
using
客户端_tcpclient
using System;
using System.Net.Sockets;
using System.Text;
namespace tcpclient
{
class Program {
static void Main(string[] args) {
//当我们创建tcpclient对象的时候,就会跟server去建立连接
TcpClient client = new TcpClient("192.168.0.112",7788);
NetworkStream stream = client.GetStream();//通过网络流进行数据的交换
//read用来读取数据,write用来写入数据其实就是发送数据
//利用一个死循环,重复向服务器端发送数据
while (true)
{
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
}
}
}
}
Udpclient
Udp协议不需要做链接,客户端是服务器端,服务器端也是客户端。
Udp服务器端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace udpclient
{
class Program {
static void Main(string[] args) {
//创建udpclient 绑定ip跟端口号
UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.114.238"),7788));
while (true)
{
//接收数据
IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
//通过point确定数据来自哪个ip的哪个端口号 返回值是一个字节数组,就是我们的数据
byte[] data = udpClient.Receive(ref point);
string message = Encoding.UTF8.GetString(data);
Console.WriteLine("收到了消息:" + message);
}
}
}
}
Udp客户端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace udpclient
{
class Program {
static void Main(string[] args) {
//创建udpclient对象
UdpClient client = new UdpClient();
while (true)
{
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.168.0.112"), 7788));
}
}
}
}
总结
学习siki的C#教程,打基础。
该套视频在泰课在线搜索《第三季 C#编程高级篇》,可以在线学习。