最大的特点在于开启了两个线程专门执行接收消息和发送消息,从而实现任意通信
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TcpServer
{
class Program
{
private static Socket clientSocket;
static void Main(string[] args)
{
//建立一个套接字(Socket)
Console.WriteLine("客户端Tcp连接模式");
//绑定服务器端IP地址及端口号
Socket TcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建一个套接字socket
TcpServer.Bind(new IPEndPoint(new IPAddress(new byte[] { 192,168,1,4 }), 7788));
TcpServer.Listen(100); //开始监听,等待客户端连接,参数为最大连接数,100表示此时服务端最多允许100个客户端连接进来
//利用Accept()方法尝试与客户端建立一个连接
Console.WriteLine("开启监听...");
Console.WriteLine("开始监听,等待客户端连接");
clientSocket = TcpServer.Accept(); //暂停当前线程,直到有一个客户端连接进来,之后进行下面的代码
//accept返回一个Socket类型,使用返回的Socket和客户端做通信
//利用Send()方法向建立连接的主机发送消息
Console.WriteLine("客户端连接进来了");
new Thread(ReceiveMessage) { IsBackground = false }.Start();
new Thread(SendMessage) { IsBackground = false }.Start();
Console.ReadKey();
}
static void ReceiveMessage()
{
while (true)
{
//接受客户端发送过来的数据
try
{
byte[] data2 = new byte[1024];
int length = clientSocket.Receive(data2);//创建一个字节数组作为容器,接受来自客户端发送过来的信息
string message2 = Encoding.UTF8.GetString(data2, 0, length);//把字节数据转化为一个字符串
Console.WriteLine(message2);
}
catch (System.Net.Sockets.SocketException)
{
}
}
}
static void SendMessage()
{
while (true)
{
//向客户端发送数据
try
{
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message); //对字符串进行编码,得到一个字符串的字节数组
clientSocket.Send(data); //只能发送byte字节,如果要发送字符串必须先将其转化为byte数组
}
catch (System.Net.Sockets.SocketException)
{
}
}
}
}
}