SOCKET用于在两个基于TCP/IP协议的应用程序之间相互通信
首先先引用
class="code_img_closed" src="/Upload/Images/2013102914/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('2be3e49f-fedc-4b15-bdc7-5f8594056f10',event)" src="/Upload/Images/2013102914/2B1B950FA3DF188F.gif" alt="" />using System.Net; using System.Net.Sockets;View Code
使用说明:先执行Server,再执行Client
Server 服务器端
1 static void Main(string[] args) 2 { 3 int port = 2000; 4 string host = "127.0.0.1"; 5 /**/ 6 ///创建终结点(EndPoint) 7 8 IPAddress ip = IPAddress.Parse(host);//把Ip地址字符串转 换为IPAddress类型的实例 9 IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例 10 11 /**/ 12 ///创建socket并开始监听 13 //创建一个socket对象,如果用udp协议,则要用SocketType.Dgram类型的套接字 14 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 15 s.Bind(ipe);//绑定EndPoint对象(2000端口和ip地址) 16 s.Listen(0);//开始监听 17 Console.WriteLine("等待客户端连接"); 18 Console.ReadLine(); 19 20 21 /**/ 22 ///接受到client连接,为此连接建立新的socket,并接受信息 23 Socket temp = s.Accept();//为新建连接创建新的socket 24 Console.WriteLine("建立连接"); 25 string recvStr = ""; 26 byte[] recvBytes = new byte[1024]; 27 int bytes; 28 bytes = temp.Receive(recvBytes,recvBytes.Length,0);//从客户端接受信息 29 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); 30 Console.ReadLine(); 31 32 33 /**/ 34 ///给client端返回信息 35 Console.WriteLine("server get message:{0}",recvStr);//把客户端传来的信息显示出来; 36 string sendStr = "ok!Client send message successful!"; 37 byte[] bs = Encoding.ASCII.GetBytes(sendStr); 38 temp.Send(bs,bs.Length,0);//返回信息给客户端 39 temp.Close(); 40 s.Close(); 41 Console.ReadLine(); 42 43 }View Code
Client 客户端
static void Main(string[] args) { try { int port = 2000; string host = "127.0.0.1"; /**/ ///创建终结点EndPoint IPAddress ip = IPAddress.Parse(host); 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);//显示服务器返回信息 Console.ReadLine(); /**/ ///一定记着用完socket后要关闭t c.Close(); } catch (ArgumentNullException e) { Console.WriteLine("argumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException:{0}", e); } Console.WriteLine("Press Enter to Exit"); }View Code