旗下导航:搜·么
当前位置:网站首页 > .Net教程 > 正文

C#和PHP Socket服务器与客户端通讯实例代码(图)【C#.Net教程】,C#,PHP,Socket

作者:搜教程发布时间:2019-11-27分类:.Net教程浏览:70评论:0


导读:这个例子只是简朴完成了怎样运用Socket类完成面向衔接的通讯。注重:此例子的目标只是为了申明用套接字写顺序的也许思绪,而不是现实项目中的运用顺序。在这个例子中,现实上...
这个例子只是简朴完成了怎样运用 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);
?>

以上就是C#和PHP Socket服务器与客户端通讯实例代码(图)的细致内容,更多请关注ki4网别的相干文章!

标签:C#PHPSocket


欢迎 发表评论: