socket socket讲解
一.socket是何物?
参考百度百科:
http://baike.baidu.com/link?url=4YNURsJLEaL0II79C68gPUoYKliXWJLM8V6H5QL0r_QOEmrxSQsnFPYxeuBx1U1bukTcAxhcl1glTOjxiGZBgSqb5G9_4N9Dj-XX-jXtXba
二.socket常用类及函数讲解:(为如下demo做准备)
IPAddress:
IPAddress.Parse();
IPEndPoint:
Encoding:
Encoding.Unicode.GetString()
Encoding.Unicode.GetBytes()
Socket:
Send、Receive、Accept;
Thread:
Thread.Sleep();
三.Demo:(仅供参考)
1.Client code:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Net.Sockets; 10 using System.Net; 11 using System.Threading; 12 13 namespace ClientSocket_Demo 14 { 15 public partial class Client : Form 16 { 17 public Client() 18 { 19 InitializeComponent(); 20 Control.CheckForIllegalCrossThreadCalls = false; 21 } 22 23 private Socket connSocket; 24 private Thread ReceiveThread; 25 26 private void btnConnection_Click(object sender, EventArgs e) 27 { 28 if (string.IsNullOrEmpty(txtIp.Text)) 29 { 30 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "ip is null"); 31 return; 32 } 33 if (string.IsNullOrEmpty(txtPort.Text)) 34 { 35 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "port is null"); 36 return; 37 } 38 Connection(); 39 } 40 41 private void btnSend_Click(object sender, EventArgs e) 42 { 43 if (string.IsNullOrEmpty(txtMsg.Text)) 44 { 45 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "msg is null"); 46 return; 47 } 48 SendMsg(); 49 } 50 51 /// <summary> 52 /// connection 53 /// </summary> 54 private void Connection() 55 { 56 IPAddress ip = IPAddress.Parse(txtIp.Text); 57 IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(txtPort.Text)); 58 connSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 59 try 60 { 61 connSocket.Connect(endPoint); 62 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "connection success."); 63 btnConnection.Enabled = false; 64 65 } 66 catch (Exception ex) 67 { 68 connSocket.Close(); 69 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "connection fail."); 70 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString()); 71 } 72 73 ReceiveThread = new Thread(ReceiveCallBack); 74 ReceiveThread.Start(); 75 ReceiveThread.IsBackground = true; 76 } 77 78 /// <summary> 79 /// send msg 80 /// </summary> 81 private void SendMsg() 82 { 83 byte[] buffer = new byte[1024]; 84 string msg = txtMsg.Text; 85 lstLog.Items.Add(DateTime.Now.ToString() + ":" + msg); 86 buffer = Encoding.Unicode.GetBytes(msg); 87 88 if (connSocket != null) 89 { 90 connSocket.Send(buffer); 91 } 92 else 93 { 94 connSocket.Close(); 95 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "send fail."); 96 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "no connection!"); 97 } 98 } 99 100 /// <summary> 101 /// receive 102 /// </summary> 103 private void ReceiveCallBack() 104 { 105 byte[] buffer = new byte[1024]; 106 int count = 0; 107 108 while (true) 109 { 110 Thread.Sleep(1000); 111 try 112 { 113 count = connSocket.Receive(buffer); 114 if (count == 0) 115 { 116 connSocket.Close(); 117 lstLog.Items.Add(DateTime.Now.ToString() + ":server disconnect."); 118 break; 119 } 120 string msg = Encoding.Unicode.GetString(buffer,0, count); 121 lstLog.Items.Add(DateTime.Now.ToString() + ":" + msg); 122 } 123 catch (Exception ex) 124 { 125 connSocket.Close(); 126 lstLog.Items.Add(DateTime.Now.ToString() + ":server disconnect."); 127 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString()); 128 break; 129 } 130 } 131 } 132 } 133 }
2.Server code:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Net; 8 using System.Net.Sockets; 9 using System.Text; 10 using System.Threading; 11 using System.Windows.Forms; 12 13 namespace Socket_Demo 14 { 15 public partial class Server : Form 16 { 17 public Server() 18 { 19 InitializeComponent(); 20 Control.CheckForIllegalCrossThreadCalls = false; 21 } 22 23 private Socket connSocket; 24 private Thread listenThread; 25 private Thread ReceiveThread; 26 27 private void button1_Click(object sender, EventArgs e) 28 { 29 if (string.IsNullOrEmpty(txtIp.Text)) 30 { 31 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "ip is null"); 32 return; 33 } 34 if (string.IsNullOrEmpty(txtPort.Text)) 35 { 36 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "port is null"); 37 return; 38 } 39 Start(); 40 } 41 42 /// <summary> 43 /// start 44 /// </summary> 45 private void Start() 46 { 47 byte[] buffer = new byte[1024]; 48 IPAddress ip = IPAddress.Parse(txtIp.Text); 49 IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(txtPort.Text)); 50 connSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 51 connSocket.Bind(endPoint); 52 connSocket.Listen(10); 53 lstLog.Items.Add(DateTime.Now.ToString() + ":" + "listen:" + txtPort.Text); 54 button1.Enabled = false; 55 56 //监听线程 57 listenThread = new Thread(ListenCallBack); 58 listenThread.Start(connSocket); 59 listenThread.IsBackground = true; 60 } 61 62 /// <summary> 63 /// listen 64 /// </summary> 65 /// <param name="o"></param> 66 private void ListenCallBack(object obj) 67 { 68 string ip = string.Empty; 69 70 //创建监听套接字 71 Socket listenSocket = obj as Socket; 72 73 while (true) 74 { 75 Thread.Sleep(1000); 76 77 try 78 { 79 //创建通信套接字 80 Socket socket = listenSocket.Accept(); 81 ip = socket.RemoteEndPoint.ToString(); 82 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ip + " connect success."); 83 84 //通信线程 85 ReceiveThread = new Thread(ReceiveCallBack); 86 ReceiveThread.Start(socket); 87 ReceiveThread.IsBackground = true; 88 } 89 catch (Exception ex) 90 { 91 listenSocket.Close(); 92 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString()); 93 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ip + " connect fail."); 94 break; 95 } 96 } 97 } 98 99 /// <summary> 100 /// receive 101 /// </summary> 102 /// <param name="o"></param> 103 private void ReceiveCallBack(object o) 104 { 105 byte[] buffer = new byte[1024]; 106 int count = 0; 107 string ip = string.Empty; 108 109 Socket ReceiveSocket = o as Socket; 110 111 while (true) 112 { 113 Thread.Sleep(1000); 114 try 115 { 116 ip = ReceiveSocket.RemoteEndPoint.ToString(); 117 count = ReceiveSocket.Receive(buffer); 118 if (count == 0) 119 { 120 ReceiveSocket.Close(); 121 lstLog.Items.Add(DateTime.Now.ToString() + ":client disconnect."); 122 break; 123 } 124 string msg = Encoding.Unicode.GetString(buffer, 0, count); 125 lstLog.Items.Add(DateTime.Now.ToString() + ":" + msg); 126 } 127 catch (Exception ex) 128 { 129 ReceiveSocket.Close(); 130 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ip + "client disconnect."); 131 lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString()); 132 break; 133 } 134 } 135 } 136 137 private void Server_Load(object sender, EventArgs e) 138 { 139 var localhostIp = Dns.GetHostEntry(Dns.GetHostName()).AddressList[5]; 140 txtIp.Text = localhostIp.ToString(); 141 txtPort.Text = "8000"; 142 } 143 } 144 }
四.注意事项: