This example simply implements how to use the Socket class to implement connection-oriented communication.
Note: The purpose of this example is to illustrate the general idea of writing a program with sockets, rather than using the program in the actual project. In this case, there are actually many problems that are not solved, such as the message boundary problem, whether the port number is occupied, the parsing of the message command, and so on.
The following is the code for two programs ( two programs are console programs )
The complete code for the first outgoing server is as follows:
Introduce a namespace:
Using system.net.sockets;using system.net;using system.threading;
The complete code is as follows:
Namespace Socketserver{class Program {private static byte[] result = new byte[1024]; private static int myprot = 8885; Port static Socket ServerSocket; static void Main (string[] args) {//server IP address IPAddress ip = ipaddress.parse ("127.0.0.1"); ServerSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Serversocket.bind (New IPEndPoint (IP, Myprot)); Bind IP Address: Port Serversocket.listen (10); Set up to 10 queued connection requests Console.WriteLine ("Boot listener {0} succeeded", ServerSocket.LocalEndPoint.ToString ()); Send data via clientsoket thread myThread = new Thread (listenclientconnect); Mythread.start (); Console.ReadLine (); }///<summary>//Monitoring Client connection///</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>//Reception///</summary>//<param name= "Clientsocket" ></param> private static void ReceiveMessage (object clientsocket) {Socket Myclientsocke t = (Socket) clientsocket; while (true) {try {///Receive data by Clientsocket int Receivenum ber = myclientsocket.receive (result); Console.WriteLine ("Receive client {0} message {1}", MyClientSocket.RemoteEndPoint.ToString (), Encoding.ASCII.GetString (result, 0, Receivenumber)); } catch (Exception ex) {Console.WriteLine (ex. Message); Myclientsocket.shutdown (Socketshutdown.both); MycliEntsocket.close (); Break } } } }}
The above is the complete code for the server side.
The complete code for the client is as follows:
Introduce a namespace:
Using system.net;using system.net.sockets;using system.threading;
Full code:
Namespace Socketclient{class Program {private static byte[] result = new byte[1024]; static void Main (string[] args) {//Set server IP address 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));//configure server IP with Port Console.writel INE ("Connection server succeeded"); } catch {Console.WriteLine ("The connection server failed, please press ENTER to exit!") "); Return }//Receive data by Clientsocket int receivelength = clientsocket.receive (result); Console.WriteLine ("Receive Server message: {0}", Encoding.ASCII.GetString (Result,0,receivelength)); Send data via clientsocket for (int i = 0; i <; i++) {try { Thread.Sleep (1000); Wait 1 seconds String sendMessage = "Client send Message HELLP" + datetime.now; Clientsocket.send (Encoding.ASCII.GetBytes (sendMessage)); Console.WriteLine ("Send message to server: {0}" + sendMessage); } catch {Clientsocket.shutdown (Socketshutdown.both); Clientsocket.close (); Break }} Console.WriteLine ("Send finished, press ENTER to exit"); Console.ReadLine (); } }}
After the compilation succeeds, the service side (server) is run and the client is run to achieve the communication effect.
Effects such as:
The program has passed the LAN test. (192.168.x.x)
PHP socket Communication (TCP/UDP)
Attention
1. The IP address cannot be a true loopback address, such as 127.0.0.1, when Socket_bind
2.server.php backstage run up when nohup php server.php >/var/tmp/a.log 2>&1 &
One: UDP mode
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, 1024x768, 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);? >
One: TCP mode
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, 1024x768); 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);?