yyyyyyyyyyyyyyyyyyyy

博客园 首页 新随笔 联系 订阅 管理

C#写的客户端连接 php的服务器端的小例子

php的server 端

  1. <?php
  2.  
  3. // server.php
  4. set_time_limit( 0 );
  5. ob_implicit_flush();
  6. $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
  7. socket_bind( $socket, '127.0.0.1', 8880 );
  8. socket_listen($socket);
  9. $acpt=socket_accept($socket);
  10. echo "> Acpt!\n";
  11. while ( $acpt ) {
  12.     echo "> ";
  13.     $words= trim(fgets(STDIN));
  14.     if(strlen($words) === 0) $words = "\n";
  15.     socket_write($acpt,$words);
  16.     $hear=socket_read($acpt,1024);
  17.     echo "client>" . $hear . "\n" ;
  18.     if("bye"==$hear){
  19.         socket_shutdown($acpt);
  20.         break;
  21.     }
  22.     usleep( 1000 );
  23. }
  24. socket_close($socket);
  25. echo "> bye bye\n";
  26. ?>

以交互式方法运行:

  1. php -a server.php



C#写的客户端


  1. public class Client
  2.     {
  3.         private static byte[] result = new byte[1024];
  4.         public string serverIp = "127.0.0.1";
  5.         public int severPort = 8880;

  6.         public Client(string serverIp, int serverPort)
  7.         {
  8.             this.serverIp = serverIp;
  9.             this.severPort = serverPort;
  10.         }

  11.         public void start()
  12.         {
  13.             //设定服务器IP地址
  14.             IPAddress ip = IPAddress.Parse(serverIp);
  15.             Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  16.             try {
  17.                 clientSocket.Connect(new IPEndPoint(ip, severPort));
  18.                 Console.WriteLine("连接服务器成功");
  19.             } catch {
  20.                 Console.WriteLine("连接服务器失败");
  21.                 return;
  22.             }

  23.             int receiveLength;
  24.             while (clientSocket.Connected) {

  25.                 receiveLength = clientSocket.Receive(result);
  26.                 string sv_word = Encoding.ASCII.GetString(result, 0, receiveLength);
  27.                 Console.WriteLine("Sever> {0}", sv_word);

  28.                 if (sv_word.Trim() == "bye") break;

  29.                 Console.Write("> ");
  30.                 string words = Console.ReadLine();
  31.                 if (string.IsNullOrEmpty(words)) words = "\n";
  32.                 clientSocket.Send(Encoding.ASCII.GetBytes(words));

  33.                 if (words.Trim() == "bye") break;


  34.             }
  35.             
  36.            if(clientSocket.Connected) clientSocket.Close();
  37.            Console.WriteLine("> bye bye");
  38.             
  39.         }
  40.     }


加入引入

  1. using System.Net;
  2. using System.Net.Sockets;
  3. using System.Threading;


在某处调用

  1. new Client("127.0.0.1", 8880).start();

 

posted on 2015-09-04 12:38  xxxxxxxx1x2xxxxxxx  阅读(260)  评论(0编辑  收藏  举报