這個例子只是簡單實現了如何使用 Socket 類實現連線導向的通訊。
注意:此例子的目的只是為了說明用通訊端寫程式的大概思路,而不是實際項目中的使用程式。在這個例子中,實際上還有很多問題沒有解決,如訊息邊界問題、連接埠號碼是否被佔用、訊息命令的解析問題等。。
下面是兩個程式的代碼,(兩個程式均為控制台程式)
先發服務端的(Server)完整代碼如下:
引入命名空間:
using System.Net.Sockets;using System.Net;using System.Threading;
完整代碼如下:
namespace SocketServer{ class Program { private static byte[] result = new byte[1024]; private static int myProt = 8885; //連接埠 static Socket serverSocket; static void Main(string[] args) { //伺服器IP地址 IPAddress ip = IPAddress.Parse("127.0.0.1"); serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(ip, myProt)); //綁定IP地址:連接埠 serverSocket.Listen(10); //設定最多10個排隊串連請求 Console.WriteLine("啟動監聽{0}成功", serverSocket.LocalEndPoint.ToString()); //通過Clientsoket發送資料 Thread myThread = new Thread(ListenClientConnect); myThread.Start(); Console.ReadLine(); } /// <summary> /// 監聽用戶端串連 /// </summary> private static void ListenClientConnect() { while (true) { Socket clientSocket = serverSocket.Accept(); clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello")); Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientSocket); } } /// <summary> /// 接收訊息 /// </summary> /// <param name="clientSocket"></param> private static void ReceiveMessage(object clientSocket) { Socket myClientSocket = (Socket)clientSocket; while (true) { try { //通過clientSocket接收資料 int receiveNumber = myClientSocket.Receive(result); Console.WriteLine("接收用戶端{0}訊息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)); } catch(Exception ex) { Console.WriteLine(ex.Message); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); break; } } } }}
以上是服務端(server)的完整代碼。
用戶端(Client)的完整代碼如下:
引入命名空間:
using System.Net;using System.Net.Sockets;using System.Threading;
完整代碼:
namespace SocketClient{ class Program { private static byte[] result = new byte[1024]; static void Main(string[] args) { //設定伺服器IP地址 IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(new IPEndPoint(ip, 8885)); //設定管理員IP與連接埠 Console.WriteLine("串連伺服器成功"); } catch { Console.WriteLine("串連伺服器失敗,請按斷行符號鍵退出!"); return; } //通過clientSocket接收資料 int receiveLength = clientSocket.Receive(result); Console.WriteLine("接收伺服器訊息:{0}",Encoding.ASCII.GetString(result,0,receiveLength)); //通過 clientSocket 發送資料 for (int i = 0; i < 10; i++) { try { Thread.Sleep(1000); //等待1秒鐘 string sendMessage = "client send Message Hellp" + DateTime.Now; clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage)); Console.WriteLine("向伺服器發送訊息:{0}" + sendMessage); } catch { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); break; } } Console.WriteLine("發送完畢,按斷行符號鍵退出"); Console.ReadLine(); } }}
編譯成功後,先運行 服務端(server),再運行用戶端(client)即可達到通訊效果。
效果如:
該程式已在區域網路測試通過。(192.168.X.X)
php socket通訊(tcp/udp)
注意
1.在socket_bind的時候ip地址不能真迴環地址如127.0.0.1
2.server.php後台跑起來的時候 nohup php server.php > /var/tmp/a.log 2>&1 &
一: udp 方式
1) server.php
<?php//error_reporting( E_ALL );set_time_limit( 0 );ob_implicit_flush();$socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );if ( $socket === false ) { echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n";}$ok = socket_bind( $socket, '202.85.218.133', 11109 );if ( $ok === false ) { echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) );}while ( true ) { $from = ""; $port = 0; socket_recvfrom( $socket, $buf,1024, 0, $from, $port ); echo $buf; usleep( 1000 );}?>
2) client.php
<?php$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);$msg = 'hello';$len = strlen($msg);socket_sendto($sock, $msg, $len, 0, '202.85.218.133', 11109);socket_close($sock);?>
一: TCP 方式
1)server.php
<?php//error_reporting( E_ALL );set_time_limit( 0 );ob_implicit_flush();$socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );socket_bind( $socket, '192.168.2.143', 11109 );socket_listen($socket);$acpt=socket_accept($socket);echo "Acpt!\n";while ( $acpt ) { $words=fgets(STDIN); socket_write($acpt,$words); $hear=socket_read($acpt,1024); echo $hear; if("bye\r\n"==$hear){ socket_shutdown($acpt); break; } usleep( 1000 );}socket_close($socket)?>
2) client.php
<?php$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);$con=socket_connect($socket,'192.168.2.143',11109);if(!$con){socket_close($socket);exit;}echo "Link\n";while($con){ $hear=socket_read($socket,1024); echo $hear; $words=fgets(STDIN); socket_write($socket,$words); if($words=="bye\r\n"){break;}}socket_shutdown($socket);socket_close($sock);?>