端口號和ip地址自己改壹下
using System.Net;
using System.Net.Sockets;
static void Main(string[] args)//服務器段
{
int port = 2000;
string host = "127.0.0.1";
/**/
///創建終結點(EndPoint)
IPAddress ip = IPAddress.Parse(host);//把ip地址字符串轉換為IPAddress類型的實例
IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint類的新實例
/**/
///創建socket並開始監聽
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建壹個socket對像,如果用udp協議,則要用SocketType.Dgram類型的套接字
s.Bind(ipe);//綁定EndPoint對像(2000端口和ip地址)
s.Listen(0);//開始監聽
Console.WriteLine("等待客戶端連接");
/**/
///接受到client連接,為此連接建立新的socket,並接受信息
Socket temp = s.Accept();//為新建連接創建新的socket
Console.WriteLine("建立連接");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//從客戶端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
/**/
///給client端返回信息
Console.WriteLine("server get message:{0}", recvStr);//把客戶端傳來的信息顯示出來
string sendStr = "ok!Client send message successful!";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
temp.Send(bs, bs.Length, 0);//返回信息給客戶端
temp.Close();
s.Close();
Console.ReadLine();
}
static void Main(string[] args)//客戶端
{
try
{
int port = 2000;
string host = "127.0.0.1";
/**/
///創建終結點EndPoint
IPAddress ip = IPAddress.Parse(host);
//IPAddress ipp = new IPAddress("127.0.0.1");
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口轉化為IPEndpoint實例
/**/
///創建socket並連接到服務器
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建Socket
Console.WriteLine("Conneting…");
c.Connect(ipe);//連接到服務器
/**/
///向服務器發送信息
string sendStr = "hello!This is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字符串編碼為字節
Console.WriteLine("Send Message");
c.Send(bs, bs.Length, 0);//發送信息
/**/
///接受從服務器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = c.Receive(recvBytes, recvBytes.Length, 0);//從服務器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("client get message:{0}", recvStr);//顯示服務器返回信息
/**/
///壹定記著用完socket後要關閉
c.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("argumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException:{0}", e);
}
Console.WriteLine("Press Enter to Exit");
}