服务端:
static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Thread th = new Thread(rec);
th.IsBackground = true;
th.Start();
try
{
clientSocket.Connect(new IPEndPoint(ip, 8888)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
//通过 clientSocket 发送数据
for (int i = 0; i < 10; i++)
{
try
{
string ss = Console.ReadLine();
clientSocket.Send(Encoding.ASCII.GetBytes(ss));
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.ReadLine();
}
static public void rec()
{
while (true)
{
//通过clientSocket接收数据
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
}
}
客户端:
private static byte[] result = new byte[1024];
static Socket serverSocket;
static void Main(string[] args)
{
//服务器IP地址
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888)); //绑定IP地址:端口
serverSocket.Listen(10); //设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
static int i = 0;
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
myClientSocket.Send(Encoding.Unicode.GetBytes(i.ToString()));
i += 1;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}