客户端代码:
Socket ClientSocket;
String IP = "127.0.0.1";
int port = 19222;
IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
ClientSocket.Connect(endPoint); //与远程主机建立连接
listadd("上报账号密码中。。。");
byte[] message = Encoding.UTF8.GetBytes("/" + username + "//" + password + "///"); //通信时实际发送的是字节数组,所以要将发送消息转换字节
ClientSocket.Send(message);
listadd("发送消息为:" + Encoding.UTF8.GetString(message));
byte[] receive = new byte[1024];
int length = ClientSocket.Receive(receive); // length 接收字节数组长度
listadd("返回消息为:" + Encoding.UTF8.GetString(receive));
ClientSocket.Close(); //关闭连接
if (Encoding.UTF8.GetString(receive) == "0")
{
listadd("登录成功!");
}
if (Encoding.UTF8.GetString(receive) == "1")
{
listadd("密码错误!");
}
if (Encoding.UTF8.GetString(receive) == "2")
{
listadd("用户未找到!");
}
服务端代码:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPAddress iPAddress = IPAddress.Parse("0.0.0.0");
IPEndPoint endPoint = new IPEndPoint(iPAddress, 19222);
socket.Bind(endPoint);
socket.Listen(10); //设定最多有10个排队连接请求
Console.WriteLine("建立连接");
Socket socket1 = socket.Accept();
byte[] receive = new byte[1024];
socket1.Receive(receive);
string recv_msg = Encoding.UTF8.GetString(receive);
Console.WriteLine("接收到消息:" + recv_msg);
string username = MidStrEx_New(recv_msg, "/", "//");
string password = MidStrEx_New(recv_msg, "//", "///");
Console.WriteLine("账户:");
Console.WriteLine(username);
Console.WriteLine("密码:");
Console.WriteLine(password);
Console.WriteLine("解密后的密码:");
Console.WriteLine(Decode(password));
byte[] send = Encoding.UTF8.GetBytes("0");
socket1.Send(send);
Console.WriteLine("发送消息为:" + Encoding.UTF8.GetString(send));