版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/yangwohenmai1/article/details/92589072
对于Socket来说,链接类型一般分为长连接和短连接。
长连接和短连接在程序上基本没有区别,区别是短连接每次发送完消息都要调用Close()方法来释放资源,而长连接则不调用Close()方法,从而保持持续不断的通信功能。
GitHub代码服务端:https://github.com/yangwohenmai/TEST/tree/master/SocketServer
GitHub代码客户端:https://github.com/yangwohenmai/TEST/tree/master/SocketClient
分为两个项目,一个Socket服务端和一个Socket客户端。结构如下:
Socket长连接效果图如下,可以持续的发送消息,不需要重复链接:
Socket服务端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketServer
{
class Program
{
static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
SocketServie();
}
public static void SocketServie()
{
Console.WriteLine("服务端已启动");
string host = "127.0.0.1";//IP地址
int port = 2000;//端口
socket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
socket.Listen(100);//设定最多100个排队连接请求
Thread myThread = new Thread(ListenClientConnect);//通过多线程监听客户端连接
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// 监听客户端连接
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = socket.Accept();
clientSocket.Send(Encoding.UTF8.GetBytes("我是服务器"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
if (receiveNumber == 0)
return;
Console.WriteLine("接收客户端{0} 的消息:{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(result, 0, receiveNumber));
//给Client端返回信息
string sendStr = "已成功接到您发送的消息";
byte[] bs = Encoding.UTF8.GetBytes(sendStr);//Encoding.UTF8.GetBytes()不然中文会乱码
myClientSocket.Send(bs, bs.Length, 0); //返回信息给客户端
//myClientSocket.Close(); //发送完数据关闭Socket并释放资源//长连接的话就不关闭
//Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Close();//关闭Socket并释放资源
myClientSocket.Shutdown(SocketShutdown.Both);//禁止发送和上传
break;
}
}
}
}
}
Socket客户端代码:
代码中包含两个方法,分别是长连接和短连接方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SocketClient
{
class Program
{
static void Main(string[] args)
{
//短连接
shotlink("");
//长连接
//longlink();
}
/// <summary>
/// 短连接,最后调用Close释放资源
/// </summary>
/// <param name="input"></param>
public static void shotlink(string input)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 2000)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
Console.ReadLine();
return;
}
string sendMessage = "你好";//发送到服务端的内容
clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));//向服务器发送数据,需要发送中文则需要使用Encoding.UTF8.GetBytes(),否则会乱码
Console.WriteLine("向服务器发送消息:" + sendMessage);
//接受从服务器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0); //从服务器端接受返回信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
Console.WriteLine("服务端发来消息:{0}", recvStr);//回显服务器的返回信息
//每次完成通信后,关闭连接并释放资源
clientSocket.Close();
Console.ReadLine();
}
/// <summary>
/// 长连接不调用Close释放资源
/// </summary>
public static void longlink()
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 2000)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
Console.ReadLine();
return;
}
//循环读取输入数据
while (true)
{
Console.WriteLine("请输入");
string sentstr = Console.ReadLine();
SentMsg(sentstr, clientSocket);
}
}
/// <summary>
/// 长连接,不释放资源
/// </summary>
/// <param name="sentstr"></param>
/// <param name="clientSocket"></param>
public static void SentMsg(string sentstr, Socket clientSocket)
{
string sendMessage = "你好";//发送到服务端的内容
sendMessage = sentstr;//发送到服务端的内容
//向服务器发送数据,需要发送中文则需要使用Encoding.UTF8.GetBytes(),否则会乱码
clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:" + sendMessage);
//接受从服务器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0); //从服务器端接受返回信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
Console.WriteLine("服务端发来消息:{0}", recvStr); //回显服务器的返回信息
//clientSocket.Close();//关闭连接并释放资源//如果是长连接,注释掉close
}
}
}
附一些学习链接:
TCP/IP详解--TIME_WAIT状态详解:https://blog.csdn.net/yusiguyuan/article/details/21445773
socket的TIME_WAIT状态的原因及解决办法和避免的办法:https://blog.csdn.net/windyf2013/article/details/78756791
Socket的长连接和短连接:https://www.cnblogs.com/lcplcpjava/p/6581179.html
HTTP长连接、短连接究竟是什么?:https://www.cnblogs.com/gotodsp/p/6366163.html
socket shutdown和close的区别:https://www.cnblogs.com/kex1n/p/7146054.html
一篇搞懂TCP、HTTP、Socket、Socket连接池:https://blog.csdn.net/liuchaoxuan/article/details/81624311
socket连接池:https://blog.csdn.net/nokianasty/article/details/8554577
————————————————
版权声明:本文为CSDN博主「佚名兄」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yangwohenmai1/article/details/92589072