分类:
C#
服务器端代码:
客户端代码:
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Net;
-
using System.Net.Sockets;
-
-
-
namespace multithreadclientTest
-
{
-
class Program
-
{
-
/// <summary>
-
/// 本程序代码的主要功能:
-
/// (1)创建套接字,并通过connect方法连接到本地终结点。当连接建立以后,便可以与服务器进
-
/// 行通讯了。
-
/// (2)在客户端上等待用户输入一条消息,该消息会发送到服务器创建的消息服务线程上
-
/// 的ClientService 方法上进行处理。在将该消息转化为大写字母后,发还给客户端。
-
/// 这是一个echo技术。如果在控制台上输入exit 接断开与服务器之间的连接。
-
/// </summary>
-
/// <param name='args'></param>
-
static void Main(string[] args)
-
{
-
Socket client;
-
byte[] buf = new byte[1024];
-
string input;
-
IPAddress local = IPAddress.Parse('192.168.5.187');
-
IPEndPoint iep = new IPEndPoint(local, 13000);
-
-
try
-
{
-
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
-
ProtocolType.Tcp);
-
client.Connect(iep);
-
}
-
catch (SocketException)
-
{
-
Console.WriteLine('无法连接到服务器!');
-
return;
-
}
-
finally
-
{
-
-
}
-
while (true)
-
{
-
//在控制台上输入一条消息
-
input = Console.ReadLine();
-
//输入exit,可以断开与服务器的连接
-
if (input == 'exit')
-
{
-
break;
-
}
-
client.Send(Encoding.ASCII.GetBytes(input));
-
//得到实际收到的字节总数
-
int rec = client.Receive(buf);
-
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, rec));
-
-
}
-
Console.WriteLine('断开与服务器的连接......');
-
client.Close();
-
-
-
}
-
}
-
}
程序执行部分截图:
|