概述
socket服务端
private static Socket serverSocket = null;
static void Main(string[] args)
{
//AddressFamily.InterNetwork 地址族
//SocketType.Stream 指定类型
//ProtocolType.Tcp 指定协议
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//进行绑定
//端口号范围 0-65535
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999);
serverSocket.Bind(endPoint);
//10 代表连接队列的最大长度
serverSocket.Listen(10);
//开一个线程接收客户端连接
Console.WriteLine("开始监听");
Thread thread = new Thread(listenClientConnect);
thread.Start();
while (true) { }
}
/// <summary>
/// 监听客户端连接
/// </summary>
private static void listenClientConnect()
{
//等待 有客户端连接的时候 就会触发这个函数 返回一个客户端的socket对象
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("客户端连接成功 信息:" + clientSocket.AddressFamily.ToString());
//给客户端发送一个消息
clientSocket.Send(Encoding.Default.GetBytes("服务器告诉你连接成功了"));
Thread recThread = new Thread(receiveClientMessage);
recThread.Start(clientSocket);
}
/// <summary>
/// 接收来自客户端的消息
/// </summary>
private static void receiveClientMessage(object clientSocket)
{
Socket socket = clientSocket as Socket;
byte[] buffer = new byte[1024];
//接收到数据的长度
int length = socket.Receive(buffer);
//显示出来
Console.WriteLine("收到消息 : " + Encoding.Default.GetString(buffer, 0, length));
}
socket客户端
private static Socket clientSocket = null;
static void Main(string[] args)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//客户端要连接 不需要bind
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
clientSocket.Connect(remoteEP);
Console.WriteLine("连接到远程服务器");
byte[] result = new byte[1024];
int length = clientSocket.Receive(result);
Console.WriteLine("收到消息 : " + Encoding.Default.GetString(result, 0, length));
clientSocket.Send(Encoding.Default.GetBytes("服务器你好 我是客户端"));
while (true) { }
}
最后
以上就是酷炫电源为你收集整理的C# 网络编程 socket编程入门的全部内容,希望文章能够帮你解决C# 网络编程 socket编程入门所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复