1.首先是服务器的编写:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Net;
namespace Server
{
class Program
{
private static Socket server;
static void Main(string[] args)
{
//创建一个套接字
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定端口
server.Bind(new IPEndPoint(IPAddress.Any, 10001));
//监听
server.Listen(10);//监听个数
//不断的监听
while(true)
{
Socket client = server.Accept();//接收客户端链接的信息
Console.WriteLine("有客户端连入");
//对客户端中的套接字传递过来的信息进行处理
ReceiveMessage(client);
}
}
private static void ReceiveMessage(Socket client)
{
try
{
byte[] buffer = new byte[1024];//作为数据缓冲
int size = client.Receive(buffer);
//哪一个客户端连接的,以及输出的是什么
Console.WriteLine(client.RemoteEndPoint.ToString() + ":" + Encoding.UTF8.GetString(buffer, 0, size));
ReceiveMessage(client);
}
catch (Exception)
{
Console.WriteLine("客户端断开了");
}
}
}
}
2.客户端的编写:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Program
{
private static Socket client;
private static byte[] bytearray = new byte[1024];
static void Main(string[] args)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect("127.0.0.1", 10001);
//开始从链接的socket中异步接收数据
client.BeginReceive(bytearray, 0, 1024, SocketFlags.None, ReceiveCallBack, client);
Input();
}
private static void Input()
{
string txt = Console.ReadLine();
if(txt.Trim().Equals(string.Empty))
{
Console.WriteLine("按任意键退出");
Console.Read();
return;
}
byte[] array = Encoding.UTF8.GetBytes(txt);
client.Send(array);
Input();
}
private static void ReceiveCallBack(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
try
{
int size = client.EndReceive(ar);
Console.WriteLine(Encoding.UTF8.GetString(bytearray, 0, size));
client.BeginReceive(bytearray, 0, 1024, SocketFlags.None, ReceiveCallBack, client);
}
catch (Exception)
{
Console.WriteLine("服务器把你给踢了!");
}
}
}
}