记录自己的学习过程
最近发现自己学的东西很杂,在各个文件夹下,找起来麻烦又很乱,每次参考一下以前练习的代码,都要打开很多个VS,所以利用下CSDN这个平台,做点笔记。
网络编程基础
服务器 | 客户机 |
---|
socket() | socket() | bind() | | listen() | | accept() | connect() | recv() | send() | send() | recv() | close() | close() |
代码
IPAddress类
方法 | | 字段 | |
---|
Equals | 比较两个IP地址 | Any | Any 用于代表本地系统可用的任何IP | GetHashCode | | Broadcast | 代表本地网络的IP广播地址 | GetType | | Loopback | 回送 | HostToNetworkorder | | None | 用于代表系统上没有任何网络接口 | IsLoopBack | 是否是回送地址? | | | Parse | 把一个字符串转换成IPAddress | | | ToString | | | |
class IPAdress_test
{
public void IPAdress_testRun()
{
IPAddress test6 = IPAddress.Parse("111.111.111.111");
IPAddress test2 = IPAddress.Loopback;
IPAddress test3 = IPAddress.Broadcast;
IPAddress test4 = IPAddress.Any;
IPAddress test5 = IPAddress.None;
IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
IPAddress myself = ihe.AddressList[0];
IPAddress myself2 = ihe.AddressList[1];
if (IPAddress.IsLoopback(test2))
Console.WriteLine("回送地址(loopback)是{0}", test2.ToString());
else
Console.WriteLine("获取回送地址发生错误!");
Console.WriteLine("本地IP地址是 {0}", myself.ToString());
if (myself == test2)
Console.WriteLine("回送地址和本地IP地址相同!");
else
Console.WriteLine("回送地址和本地IP地址不同!");
Console.WriteLine("The test address is:{0}", test2.ToString());
Console.WriteLine("The test address is:{0}", test3.ToString());
Console.WriteLine("The test address is:{0}", test4.ToString());
Console.WriteLine("The test address is:{0}", test5.ToString());
Console.WriteLine("The test address is:{0}", test6.ToString());
Console.WriteLine("The myself2 address is:{0}", myself2.ToString());
}
}
IPEndPoint类
方法 | | 属性 | |
---|
Create | 从一个socketAssress创建EndPoint | Address | IP地址 | Equals | 比较两个 | AddressFamily | IP系列地址 | GetHashCode | 从IPEndPoint返回散列值 | Port | 端口号 | GetType | 返回IPEndPoint实例类型 | | MaxPort | Serialize | 创建实例的SocketAddress | MinPort | 端口号最小值 | ToString | | | |
class IPEndPoint_test
{
public void IPEndPoint_testRun()
{
IPAddress test1 = IPAddress.Parse("111.111.111.111");
IPEndPoint ie = new IPEndPoint(test1, 8000);
Console.WriteLine("The IPEndPoint is: {0}", ie.ToString());
Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily);
Console.WriteLine("地址是:{0}", "端口是:{1}",ie.Address, ie.Port);
Console.WriteLine("端口最小值:{0}", IPEndPoint.MinPort);
Console.WriteLine("端口最大值:{0}", IPEndPoint.MaxPort);
ie.Port = 80;
Console.WriteLine("The changed IPEndPoint value is {0}", ie.ToString());
SocketAddress sa = ie.Serialize();
Console.WriteLine("套接字地址是:{0}", sa.ToString());
}
}
简单TCP服务器测试
class SimpleTcpServer
{
public void SimpleTcpServer_Run()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newSock.Bind(ipep);
newSock.Listen(10);
Console.WriteLine("等待连接...");
Socket Client1 = newSock.Accept();
IPEndPoint Client_ep1 = (IPEndPoint)Client1.RemoteEndPoint;
Console.WriteLine("已经连接到{0},对方端口{1}",
Client_ep1.Address, Client_ep1.Port);
string welcome = "欢迎连接到我的测试服务器!";
data = Encoding.UTF8.GetBytes(welcome);
Client1.Send(data, data.Length, SocketFlags.None);
while(true)
{
data = new byte[1024];
recv = Client1.Receive(data);
if (recv == 0)
break;
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
Client1.Send(data, recv, SocketFlags.None);
}
Console.WriteLine("关闭来自{0}的连接!", Client_ep1.Address);
Client1.Close();
newSock.Close();
}
}
简单TCP客户端测试
class SimpleTcpClient
{
public void SimpleTcpClient_Run()
{
byte[] data = new byte[1024];
string input, stringData;
IPEndPoint ipep = new IPEndPoint(
IPAddress.Parse("192.168.137.30"), 9050);
Socket server1 = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
server1.Connect(ipep);
if (server1 != null)
if (server1.RemoteEndPoint != null)
Console.WriteLine("连接成功!\n远程主机地址为{0}",
server1.RemoteEndPoint);
else
Console.WriteLine("找不到服务器!");
}
catch(SocketException e)
{
Console.WriteLine("无法连接到服务器!");
Console.WriteLine(e.ToString());
return;
}
int recv = server1.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
while(true)
{
input = Console.ReadLine();
if (input == "exit")
break;
server1.Send(Encoding.ASCII.GetBytes(input));
data = new byte[1024];
recv = server1.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("断开与服务器的连接!");
server1.Shutdown(SocketShutdown.Both);
server1.Close();
}
}
指定数据量测试
class FixedTcpServer
{
private static int SendData(Socket s,byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
while(total<size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}
private static byte[] ReceiveData(Socket s,int size)
{
int total = 0;
int dataleft = size;
byte[] data = new byte[size];
int recv;
while(total<size)
{
recv = s.Receive(data, total, dataleft, 0);
if(recv==0)
{
data = Encoding.ASCII.GetBytes("exit");
break;
}
total += recv;
dataleft -= recv;
}
return data;
}
public void FixedTcpServer_Run()
{
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newSock.Bind(ipep);
newSock.Listen(10);
Console.WriteLine("等待客户端连接!");
Socket client = newSock.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("已连接客户端{0},对方端口为{1}",
newclient.Address, newclient.Port);
string welcome = "welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
int sent = SendData(client, data);
for(int i=0;i<5;i++)
{
data = ReceiveData(client, 9);
Console.WriteLine(Encoding.ASCII.GetString(data));
}
Console.WriteLine("断开与{0}的连接!", newclient.Address);
client.Close();
newSock.Close();
}
}
网络流测试
class StreamServer
{
public void StreamServer_Run()
{
string data;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newSock.Bind(ipep);
newSock.Listen(10);
Socket client = newSock.Accept();
NetworkStream ns = new NetworkStream(client);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
string welcome = "欢迎连接测试服务器!";
sw.WriteLine(welcome);
sw.Flush();
while(true)
{
try
{
data = sr.ReadLine();
}
catch(IOException)
{
break;
}
Console.WriteLine(data);
sw.WriteLine(data);
sw.Flush();
}
Console.WriteLine("已断开与{0}的连接", (IPEndPoint)client.RemoteEndPoint);
sw.Close();
sr.Close();
ns.Close();
client.Close();
newSock.Close();
}
}
UDP通信例子
class UdpSrvrSample
{
public void Udp_Run()
{
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
UdpClient newsock = new UdpClient(ipep);
Console.WriteLine("等待连接...");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
data = newsock.Receive(ref sender);
Console.WriteLine("Message receive from {0}", sender.ToString());
Console.WriteLine(Encoding.Unicode.GetString(data, 0, data.Length));
string welcome = "欢迎连接到我的测试服务器!";
data = Encoding.Unicode.GetBytes(welcome);
newsock.Send(data, data.Length, sender);
int ii = 4;
while(ii>0)
{
ii -= 1;
data = newsock.Receive(ref sender);
Console.WriteLine(Encoding.Unicode.GetString(data, 0, data.Length));
newsock.Send(data, data.Length, sender);
}
}
}
其他例子
class TcpPollSrvr
{
public void TcpPollSrvr_Run()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newSock.Bind(ipep);
newSock.Listen(10);
Console.WriteLine("等待来自客户端的连接...");
bool result;
int i = 0;
while(true)
{
i++;
Console.WriteLine("pollong for accpet#{0}", i);
result = newSock.Poll(1000000, SelectMode.SelectRead);
if(result)
{
break;
}
}
Socket client = newSock.Accept();
IPEndPoint newClient = (IPEndPoint)client.RemoteEndPoint;
string welcome = "欢迎连接我的测试服务器!";
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
i = 0;
while(true)
{
Console.WriteLine("polling for recive #{0}...", i);
i++;
result = client.Poll(3000000, SelectMode.SelectRead);
if(result)
{
data = new byte[1024];
i = 0;
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine(
Encoding.Unicode.GetString(data, 0, recv));
client.Send(data, recv, 0);
}
}
Console.WriteLine("断开与{0}的连接!", newClient.Address);
client.Close();
newSock.Close();
}
}
class SelectTcpServer
{
public void SelectTcpServer_Run()
{
ArrayList sockList = new ArrayList(2);
ArrayList copyList = new ArrayList(2);
Socket main = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 9050);
byte[] data = new byte[1024];
string stringData;
int recv;
main.Bind(ipe);
main.Listen(2);
Socket client1 = main.Accept();
IPEndPoint ipe1 = (IPEndPoint)client1.RemoteEndPoint;
client1.Send(Encoding.Unicode.GetBytes("欢迎连接我的测试服务器!"));
Console.WriteLine("以连接到{0}", ipe1.ToString());
sockList.Add(client1);
Console.WriteLine("等待新的客户端连接!");
Socket client2 = main.Accept();
IPEndPoint ipe2 = (IPEndPoint)client2.RemoteEndPoint;
client2.Send(Encoding.Unicode.GetBytes("欢迎连接我的测试服务器!"));
Console.WriteLine("新加入一个来自{0}的连接!", ipe2.ToString());
sockList.Add(client2);
main.Close();
while(true)
{
copyList = new ArrayList(sockList);
Console.WriteLine("监测到{0}个客户端!", copyList.Count);
Socket.Select(copyList, null, null, 10000000);
foreach(Socket client in copyList)
{
data = new byte[1024];
recv = client.Receive(data);
stringData = Encoding.Unicode.GetString(data, 0, recv);
Console.WriteLine("接收到信息:\n{0}",stringData);
if (recv == 0)
{
ipe = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("客户端{0}无连接!", ipe.ToString());
client.Close();
sockList.Remove(client);
if (sockList.Count == 0)
{
Console.WriteLine("断开和最后一个客户端的连接,再见!");
return;
}
}
else
client.Send(data, recv, SocketFlags.None);
}
}
}
}
|