1.tcp协议
###tcp协议的定义:
1,TCP协议传输控制协议(TCP,Transmission Control
Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议,由IETF的RFC 793定义。TCP旨在适应支持多网络应用的分层协议层次结构。
连接到不同但互连的计算机通信网络的主计算机中的成对进程之间依靠TCP提供可靠的通信服务。TCP假设它可以从较低级别的协议获得简单的,可能不可靠的数据报服务。
原则上,TCP应该能够在从硬线连接到分组交换或电路交换网络的各种通信系统之上操作。
tcp协议的优点:
具有有序的,安全,可靠的,不容易丢包,延时性高等特点
tcp : 用于聊天,传输文件
2.TCP协议的基础连接
2.1TCP协议服务端
private static void StartService()
{
//tcp :协议端
//实例化一个Tcp协议的socket对象
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//给服务器绑定地址与端口
IPAddress ipaddress = IPAddress.Parse("192.168.218.12");
IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, 7999);
//把ip与端口绑定在Socket里面
socketServer.Bind(iPEndPoint);
//侦听
socketServer.Listen(100);
Console.WriteLine("tcp启动");
Task.Run(() =>
{
while (true)//循环等待客户端连接
{
//会等待客户端的连接,会卡在这里,不往下运行,直到有下一个宽带连接才会继续往下运行
//当有客户端连接的时候,会返回客户端连接的对象
Socket socketkint = socketServer.Accept();
byte[] byteff = encoding.GetBytes("你今天吃饭了吗");
socketkint.Send(byteff);
Task.Run(() =>
{
try
{
while (true)//循环接收数据
{
//接受数据
byte[] buffer = new byte[1024];
//返回接收到的数据大小,接收数据也会卡住,只有接收到数据的时候才会继续往下进行
int longth = socketkint.Receive(buffer);
if (longth == 0)
{
Console.WriteLine("一个客户端断开连接");
return;
}
//把字符转成字符串
string str = encoding.GetString(buffer, 0, longth);
Console.WriteLine(str);
}
}
catch (Exception ex)
{
Console.WriteLine("出现异常" + ex.Message);
return;
}
finally
{
socketkint.Close();
}
});
}
});
}
2.2TCP协议之客户端
private static void StartClient()
{
//实例化一个TCP协议的Socket对象
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//服务端的地址和端口
IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("192.168.218.12"), 7999);
try
{
//连接远程的服务端
socket.Connect(iPEndPoint);
Console.WriteLine("连接服务端成功");
}
catch (Exception ex)
{
Console.WriteLine("连接异常:" + ex.ToString());
return;
}
//循环接收数据
Task.Run(() =>
{
try
{
while (true)
{
byte[] buffer = new byte[1024];
//等待接收对方发送的数据,返回对方发送数据的长度,数据会存放在buffer里面
int length = socket.Receive(buffer);
//把byte[]转成字符串
string str = encoding.GetString(buffer, 0, length);
Console.WriteLine(str);
}
}
catch (Exception ex)
{
Console.WriteLine("出现异常:" + ex.Message);
}
finally
{
//关闭连接,释放资源
socket.Close();
}
});
//循环发送数据
Task.Run(async () =>
{
try
{
int num = 1;
while (true)
{
byte[] buffer = encoding.GetBytes("我是客户端" + num);
//发送数据
socket.Send(buffer);
num++;
//等待1000毫秒
await Task.Delay(1000);
}
}
catch (Exception ex)
{
Console.WriteLine("出现异常:" + ex.Message);
}
});
}
3.TCP之文件传输:
3.1服务端:
public static void StartFileServer()
{
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(new IPEndPoint(IPAddress.Any, 8500));
socketServer.Listen(100);
Console.WriteLine("客户端启动");
ServerAccept();
}
//等待客户端连接
private static void ServerAccept()
{
Task.Run(() =>
{
while (true)
{
//等待客户端的连接
Socket socketClient = socketServer.Accept();
Console.WriteLine("客户端上线了");
//接收客户端的消息
byte[] buffer = new byte[1024];
int length = socketClient.Receive(buffer);
//接收文件信息的消息
string str = encoding.GetString(buffer, 0, length);
string[] strs = str.Split('-');
//文件大小
long fileSize = Convert.ToInt64(strs[0]);
string fileName = strs[1];
//给客户端回复"OK"
FileStream stream = System.IO.File.Create($"F:\\dfile\\{fileName}");
socketClient.Send(encoding.GetBytes("OK"));
// 接收客户端的文件
long NowSize = 0;
Console.WriteLine("正在接收...");
while (true)
{
buffer = new byte[1024 * 10];
length = socketClient.Receive(buffer);
// 把读到的数据写入文件
stream.Write(buffer, 0, length);
NowSize += length;
//读取结束
if (NowSize == fileSize)
{
break;
}
}
stream.Close();
socketClient.Close();
}
});
}
3.2客户端:
//启动客户端
private static void ClientServer()
{
//连接服务端
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.218.12"), 8500));
string fullname = "F:\\df1\\a.txt";
//读取文件名及其后缀
string filename = Path.GetFileName(fullname);
FileStream fs = File.OpenRead(fullname);
socketClient.Send(encoding.GetBytes($"{fs.Length}-{filename}"));
//接收服务端消息"OK"
byte[] buffer = new byte[100];
int iength = socketClient.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, iength);
if (str != "OK")//不是"OK"
{
fs.Close();
socketClient.Close();
return;
}
Console.WriteLine("努力加载中...");
//发送文件
Task.Factory.StartNew(() =>
{
buffer = new byte[1024 * 10];
while (true)
{
int length = fs.Read(buffer, 0, buffer.Length);
if (length == 0)//为0是发送结束
{
fs.Close() ;
socketClient.Close();
Console.WriteLine("发送结束");
break;
}
socketClient.Send(buffer, 0, length, SocketFlags.None);
}
});
}
4.TCP之十六进制转换
4.1 服务端
private static void StartServer()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, 8500));
socket.Listen(10);
Console.WriteLine("客户端启动");
Task.Run(() =>
{
Socket socketClient = socket.Accept();
Console.WriteLine("客户上线");
while (true)
{
//收到客户端消息
byte[] buffer = new byte[1024];
int length = socketClient.Receive(buffer);
/*byte[] data = new byte[length];
string str = string.Empty;
for (int i = 0; i < length; i++)
{
str += $"{buffer[i].ToString("x2")}";
data[i] = (byte)(buffer[i] + 1);
}
Console.WriteLine("收到的客户端消息"+str);
//收到客户端消息+1给客户端回复过去
socketClient.Send(data);*/
if (length == 1)
{
byte data = buffer[0];
if (data == 0x0A)
{
byte tem = (byte)(random.Next(0, 50));
socketClient.Send(new byte[] { tem });
}
else if (data == 0x0B)
{
byte hum = (byte)(random.Next(0, 50));
socketClient.Send(new byte[] { hum });
}
}
}
});
}
4.2 客户端
private static void StartClient()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Parse("192.168.218.12"), 8500));
Task.Run(async () =>
{
while (true)
{
//socket.Send(new byte[] { 0xAA, 0xAB, 0xAC });
/* byte[] buffer = new byte[1024];
int len = socket.Receive(buffer);
string str = string.Empty;
for (int i = 0; i < len; i++)
{
str += $"{buffer[i].ToString("x2")}";
}
Console.WriteLine("发送的消息" + str);*/
int num = random.Next(0, 100);
byte cmd = (byte)(num % 2 == 0 ? 0x0A : 0x0B);
socket.Send(new byte[] { cmd });
byte[] buffer = new byte[1024];
int length = socket.Receive(buffer);
if (length == 1)
{
byte data = buffer[0];
if (cmd == 0x0A)
{
Console.WriteLine("a" + data);
}
else if (cmd == 0x0B)
{
Console.WriteLine("b" + data);
}
}
await Task.Delay(200);
}
});
}