TCPClIEnt
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpclient
{
/// <summary>
/// Class1 的摘要說明。
/// </summary>
class client
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此處添加代碼以啟動應用程序
//
byte[] data=new byte[1024];
Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Console.Write("please input the server ip:");
string ipadd=Console.ReadLine();
Console.WriteLine();
Console.Write("please input the server port:");
int port=Convert.ToInt32(Console.ReadLine());
IPEndPoint IE=new IPEndPoint(IPAddress.Parse(ipadd),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();
}
}
}