Socket Server
static void Main(string[] args)
{
int recv;//用于表示客户端发送的信息长度
byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,9050);//本机预使用的IP和端口
System.Net.Sockets.Socket newsock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);//绑定
newsock.Listen(10);//监听
Console.WriteLine("等待客户端连接...");
System.Net.Sockets.Socket client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("连接的客户端:" + clientip.Address + "端口:" + clientip.Port);
string welcome = "欢迎你!";
data = Encoding.UTF8.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);//发送信息
while (true)
{//用死循环来不断的从客户端获取信息
data = new byte[1024];
recv = client.Receive(data);
Console.WriteLine("收到信息:" + recv);
if (recv == 0)//当信息长度为0,说明客户端连接断开
break;
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
client.Send(data, recv, SocketFlags.None);
}
Console.WriteLine("断开连接:" + clientip.Address);
client.Close();
newsock.Close();
}
Socket Client
static void Main(string[] args)
{
//通讯信息
byte[] data = new byte[1024];
System.Net.Sockets.Socket newclient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("请输入服务器IP:");
string ipadd = Console.ReadLine();
Console.WriteLine();
Console.Write("请输入服务器端口号:");//预留9050
int port = Convert.ToInt32(Console.ReadLine());
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服务器的IP和端口
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
newclient.Connect(ipadd,9050);
}
catch (SocketException e)
{
Console.WriteLine("无法连接到服务器!");
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
string stringdata = Encoding.UTF8.GetString(data, 0, recv);
Console.WriteLine(stringdata);
while (true)
{
string input = Console.ReadLine();
if (input == "exit")
break;
newclient.Send(Encoding.UTF8.GetBytes(input));
data = new byte[1024];
recv = newclient.Receive(data);
stringdata = Encoding.UTF8.GetString(data, 0, recv);
Console.WriteLine(stringdata);
}
Console.WriteLine("断开与服务器通信连接!");
newclient.Shutdown(SocketShutdown.Both);
newclient.Close();
}
楼上正解,可以试试~
使用异步监听BeginAccept() , 涉及回调函数。可以看看这方面