分类: Web开发
2013-11-24 16:59:57
- 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");
- }
- }