Home  >  Article  >  Backend Development  >  C# and PHP Socket server and client communication example code (picture)

C# and PHP Socket server and client communication example code (picture)

黄舟
黄舟Original
2017-03-10 14:02:302407browse

This example simply implements how to use the Socket class to implement connection-oriented communication.

Note: The purpose of this example is only to illustrate the general idea of ​​writing a program using sockets, not the use of the program in the actual project. In this example, there are actually many issues that remain unresolved, such as message boundary issues, whether the port number is occupied, and message command parsing issues. .

The following is the code of the two programs, (Both programs are console programs)

The complete code of the first server (Server) is as follows:

Introducing the 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;   //端口
        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;
                }
            }
        }
    }
}

The above is the server (server) complete code.

The complete code of the client (Client) is as follows:

Introducing the namespace:

using System.Net;
using System.Net.Sockets;
using System.Threading;

Complete code:

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();
        }
    }
}

Compile After success, run the server first and then the client to achieve the communication effect.

The effect is as shown below:


##This program has been tested on the local area network and passed. (192.168. The true loopback address is 127.0.0.1

2. When server.php runs in the background, nohup php server.php > /var/tmp/a.log 2>&1 &

1: udp method


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, &#39;202.85.218.133&#39;, 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 = &#39;hello&#39;;
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, &#39;202.85.218.133&#39;, 11109);
socket_close($sock);
?>

1: TCP method

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, &#39;192.168.2.143&#39;, 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,&#39;192.168.2.143&#39;,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);
?>

The above is the detailed content of C# and PHP Socket server and client communication example code (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn