C#写的客户端连接 php的服务器端的小例子
php的server 端
- <?php
- // server.php
-
set_time_limit( 0 );
-
ob_implicit_flush();
-
$socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
-
socket_bind( $socket, '127.0.0.1', 8880 );
-
socket_listen($socket);
-
$acpt=socket_accept($socket);
-
echo "> Acpt!\n";
-
while ( $acpt ) {
-
echo "> ";
-
$words= trim(fgets(STDIN));
-
if(strlen($words) === 0) $words = "\n";
-
socket_write($acpt,$words);
-
$hear=socket_read($acpt,1024);
-
echo "client>" . $hear . "\n" ;
-
if("bye"==$hear){
-
socket_shutdown($acpt);
-
break;
-
}
-
usleep( 1000 );
-
}
-
socket_close($socket);
-
echo "> bye bye\n";
- ?>
以交互式方法运行:
- php -a server.php
C#写的客户端
- public class Client
- {
- private static byte[] result = new byte[1024];
- public string serverIp = "127.0.0.1";
- public int severPort = 8880;
- public Client(string serverIp, int serverPort)
- {
- this.serverIp = serverIp;
- this.severPort = serverPort;
- }
- public void start()
- {
- //设定服务器IP地址
- IPAddress ip = IPAddress.Parse(serverIp);
- Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try {
- clientSocket.Connect(new IPEndPoint(ip, severPort));
- Console.WriteLine("连接服务器成功");
- } catch {
- Console.WriteLine("连接服务器失败");
- return;
- }
- int receiveLength;
- while (clientSocket.Connected) {
- receiveLength = clientSocket.Receive(result);
- string sv_word = Encoding.ASCII.GetString(result, 0, receiveLength);
- Console.WriteLine("Sever> {0}", sv_word);
- if (sv_word.Trim() == "bye") break;
- Console.Write("> ");
- string words = Console.ReadLine();
- if (string.IsNullOrEmpty(words)) words = "\n";
- clientSocket.Send(Encoding.ASCII.GetBytes(words));
- if (words.Trim() == "bye") break;
- }
- if(clientSocket.Connected) clientSocket.Close();
- Console.WriteLine("> bye bye");
- }
- }
加入引入
-
using System.Net;
-
using System.Net.Sockets;
- using System.Threading;
在某处调用
- new Client("127.0.0.1", 8880).start();