IPAddress
类
示例:
1
| IPAddress ip = IPAddress.Parse("118.102.111.11");
|
说明:
IPEndPoint
类
示例:
1
| IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("118.102.111.11"), 1900);
|
说明:
域名解析 (DNS)
获取主机名:
获取域名对应的 IP 列表:
1
| IPHostEntry ipEntry = Dns.GetHostEntry("www.360.com");
|
成员说明:
成员 |
描述 |
ipEntry.AddressList |
IP 地址数组 |
ipEntry.Aliases |
主机的别名列表(CNAME 记录) |
ipEntry.HostName |
DNS 主机名 |
异步获取 IP 地址
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| private async void GetHostEntry() { Task<IPHostEntry> task = Dns.GetHostEntryAsync("www.e5note.top"); await task; IPHostEntry ipEntry = task.Result;
foreach (IPAddress ip in ipEntry.AddressList) { print(ip); }
foreach (string alias in ipEntry.Aliases) { print(alias); }
print(ipEntry.HostName); }
|
字符编码
简要解释:
字符编码是人为定义的一种规则,用来将文字字符与数字(二进制)之间进行映射,以便计算机存储或传输文本。
常见编码方式:
- ASCII(美国)
- GB2312(中国)
- Shift_JIS(日本)
- Euc-kr(韩国)
- Unicode(统一所有语言符号)
- UTF-8、UTF-16、UTF-32(基于 Unicode 的实现方式)
UTF-8 和 Unicode 的关系
- Unicode:是所有字符与唯一编号(码点)之间的对应集合。
- UTF-8:是 Unicode 的一种具体实现方式,采用变长编码规则,使用 1~4 个字节表示一个字符。
二进制序列化
将基础类型转为字节数组:
1 2
| byte[] bytes = BitConverter.GetBytes(1); byte[] bytes = Encoding.UTF8.GetBytes("hello world");
|
将类对象转为字节数组
示例类:
1 2 3 4 5 6 7
| public class PlayerInfo { public int lev; public string name; public short atk; public bool sex; }
|
转换方法:
1 2 3 4 5 6 7 8 9
| public byte[] ToBytes() { byte[] bytes = new byte[11 + name.Length]; BitConverter.GetBytes(lev).CopyTo(bytes, 0); Encoding.UTF8.GetBytes(name).CopyTo(bytes, 4); BitConverter.GetBytes(atk).CopyTo(bytes, 8 + name.Length); BitConverter.GetBytes(sex).CopyTo(bytes, 11 + name.Length); return bytes; }
|
二进制反序列化
示例代码:
1 2
| BitConverter.ToInt32(bytes, 0); Encoding.UTF8.GetString(bytes);
|
Socket 编程
创建 Socket 示例:
1 2 3 4 5
| Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
|
常用操作:
1 2 3 4 5 6 7
| socket.Bind(endPoint); socket.Listen(1024); socket.Shutdown(SocketShutdown.Both); socket.Close();
socket.Send(Encoding.UTF8.GetBytes(info)); int bytesRead = socket.Receive(message);
|