客户端
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("启动一个Socket客户端链接");
int port = 2018;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(ipe);
while (true)
{
Console.WriteLine("请输入发送到服务器的信息:");
string sendStr = Console.ReadLine();
if (sendStr == "exit")
break;
byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
clientSocket.Send(sendBytes);
string recStr = "";
byte[] recBytes = new byte[4096];
int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
Console.WriteLine($"服务器返回:{recStr}");
}
clientSocket.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
服务端
public static void Proccess()
{
int port = 2018;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sSocket.Bind(ipe);
sSocket.Listen(0);
Console.WriteLine("监听已经打开,请等待");
Socket serverSocket = sSocket.Accept();
Console.WriteLine("连接已经建立。。。");
while (true)
{
string recStr = "";
byte[] recByte = new byte[4096];
int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
recStr += Encoding.ASCII.GetString(recByte, 0, bytes);
Console.WriteLine("服务器端获得信息:{0}", recStr);
if (recStr.Equals("stop"))
{
serverSocket.Close();
Console.WriteLine("关闭链接。。。。");
break;
}
Console.WriteLine("请输入回发消息。。。。");
string sendStr = Console.ReadLine();
byte[] sendByte = Encoding.ASCII.GetBytes(sendStr);
serverSocket.Send(sendByte, sendByte.Length, 0);
}
sSocket.Close();
}