SocketServer 端应用程序
static void Main(string[] args)
{
IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint point = new IPEndPoint(address, 3000);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(point);
server.Listen(3);
Socket client;
byte[] buffer = new byte[1024];
int i = 0;
string data;
Console.WriteLine("等待连接...");
if ((client = server.Accept()) != null)//进程等待
{
Console.WriteLine("用户已连接...");
while (true)
{
if ((i = client.Receive(buffer)) != 0)//进程等待
{
data = System.Text.Encoding.UTF8.GetString(buffer, 0, i);
Console.WriteLine("收到的信息为{0}", data);
Console.Write("请输入回复信息:");
string input = Console.ReadLine();
client.Send(System.Text.Encoding.UTF8.GetBytes(input));
}
}
}
Console.ReadLine();
}
//*************************8888
socketClient客户端程序
static void Main(string[] args)
{
IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint point = new IPEndPoint(address, 3000);
Socket Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(point);//进程等待
Console.WriteLine("已连接到服务器...");
byte[] buffer = new byte[1024];
string data = null;
while (true)
{
Console.Write("请输入要发送的信息:");
string input;
input = Console.ReadLine();
if (input == "exit")
break;
Client.Send(System.Text.Encoding.UTF8.GetBytes(input));
int i = 0;
i = Client.Receive(buffer);//进程等待
if (i > 0)
{
Console.Write("服务器回复信息:");
data = System.Text.Encoding.UTF8.GetString(buffer, 0, i);
Console.WriteLine(data);
}
}
Console.WriteLine("断开连接...");
Client.Shutdown(SocketShutdown.Both);
Client.Close();
}