这一篇中实现最简单的socket通信
在解决方案下新建两个控制台项目(为了方便期间这里使用控制台项目)
服务器端 [ConsoleServer]
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788);
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(ipEndPoint);
listener.Listen(50);
Console.WriteLine("服务启动,开始监听");
Console.WriteLine("等待客户端连接..."); //如果没有客户端连接会在这里阻塞
Socket clientSocket = listener.Accept();
Console.WriteLine("建立连接");
clientSocket.Close();
Console.WriteLine("关闭客户端连接");
Console.ReadLine();
}
}
}
客户端[ConsoleClient]
为了尽量简单,很多参数都硬编码进去
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788);
///创建socket并连接到服务器
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("等待连接…");
serverSocket.Connect(ipEndPoint );//连接到服务器
Console.WriteLine("已连接");
serverSocket.Close();
Console.ReadLine();
}
}
}
启动服务器端
会发现输出终止在“等待客户端连接...”
启动客户端
发现正常执行到结束