标签:
C#写的客户端连接 php的服务器端的小例子
php的server 端
以交互式方法运行:
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");
- }
- }
加入引入
在某处调用
标签:
原文地址:http://www.cnblogs.com/timdes/p/4781144.html