using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Hosting;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace WebApplication1
{
public partial class login : System.Web.UI.Page
{
Socket clientsocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//socket对象
int jiazai = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnlogin_Click(object sender, EventArgs e)
{
if (txtid.Text == "" || txtpwd.Text == "" || !message.isnumber(txtid.Text))
{
Response.Write("<script>alert('账户不能为空且只能由数字组成!')</script>");
}
else
{
if (jiazai == 0)
{
IPAddress ipconn = IPAddress.Parse("192.168.43.225");
//IPAddress ip=IPAddress.Parse("192.9.101.211");
clientsocket.Connect(ipconn, 8885);//socket客户端连接
Thread td = new Thread(recive);//这里是接收线程
td.IsBackground = true;
td.Start(clientsocket);//线程开启
jiazai += 1;//开启一次之后就不用再开启了
}
string ip=jiakongge(getipv4(),20);
byte[] sen=new byte[1024];
sen = Encoding.UTF8.GetBytes(ip + "01" + jiakongge(txtid.Text, 10) + jiakongge(txtpwd.Text, 20));//这里是客户信息
clientsocket.Send(sen);
}
}
private void recive(object obj)
{
Socket ss = (Socket)obj;
while(true)
{
byte[] rec = new byte[1024];
byte[] sen = new byte[1024];
int len = ss.Receive(rec);//接收信息
if (len > 0)
{
string taojiezi = Encoding.UTF8.GetString(rec);
string answer = taojiezi.Substring(3, 1);
switch (answer)
{
case "0":
Response.Write("<script>alert('没有此用户!');</script>");//此处报错
break;
case "1":
Response.Write("<script>alert('密码错误!');</script>");
break;
case "2":
sen = Encoding.UTF8.GetBytes(jiakongge(getipv4(), 20) + "99");
ss.Send(sen);
Response.Redirect("main.aspx");
break;
case "3":
Response.Write("<script>alert('出现异常!');</script>");
break;
}
}
}
}
private static string getipv4()//获取IPv4地址
{
string hostname = Dns.GetHostName();
IPHostEntry ipentry = Dns.GetHostEntry(hostname);
for (int i = 0; i < ipentry.AddressList.Length; i++)
{
if (ipentry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
return ipentry.AddressList[i].ToString();
}
}
return "";
}
private static string jiakongge(string s,int len)//固定字符串长度,不够右补空格
{
int a;
if (string.IsNullOrEmpty(s))
{
a = 0;
return s;
}
else
{
a = s.Length;
if (a < len)
{
for (int i = 0; i < (len - a); i++)
{
s = s + " ";
}
return s;
}
else
{
return s.Substring(0,len);
}
}
}
}
}