byte[] data = new byte[1024];
Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ip), port);//服务器的IP和端口
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
newclient.Connect(ie);
}
catch (SocketException e)
{
Console.WriteLine("unable to connect to server");
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringdata);
while (true)
{
string input = Console.ReadLine();
if (input == "exit")
break;
newclient.Send(Encoding.ASCII.GetBytes(input));
data = new byte[1024];
recv = newclient.Receive(data);
stringdata = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringdata);
}
Console.WriteLine("disconnect from sercer");
newclient.Shutdown(SocketShutdown.Both);
newclient.Close();
Socket 套接字 TCP 客户端 Client 最后修改于 2011-08-05 23:53:28
上一篇