110,539
社区成员
发帖
与我相关
我的任务
分享
public partial class MainForm : Form
{
private List<User> userList = new List<User>(); /// 保存连接的所有用户
private string ServerIP;/// 服务器IP地址
private int port;/// 监听端口
private TcpListener myListener;
bool isNormalExit = false;/// 是否正常退出所有接收线程
public MainForm()
{
InitializeComponent();
lst_State.HorizontalScrollbar = true;
btn_Stop.Enabled = false;
SetServerIPAndPort();
}
/// 根据当前程序目录的文本文件‘ServerIPAndPort.txt’内容来设定IP和端口
/// 格式:127.0.0.1:8885
private void SetServerIPAndPort()
{
FileStream fs = new FileStream("ServerIPAndPort.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string IPAndPort = sr.ReadLine();
ServerIP = IPAndPort.Split(':')[0]; //设定IP
port = int.Parse(IPAndPort.Split(':')[1]); //设定端口
sr.Close();
fs.Close();
}
/// 开始监听
private void btn_Start_Click(object sender, EventArgs e)
{
myListener = new TcpListener(IPAddress.Parse(ServerIP), port);
myListener.Start();
AddItemToListBox(string.Format("开始在{0}:{1}监听客户连接", ServerIP, port));
//创建一个线程监客户端连接请求
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
btn_Start.Enabled = false;
btn_Stop.Enabled = true;
}
/// <summary>
/// 接收客户端连接
/// </summary>
private void ListenClientConnect()
{
TcpClient newClient = null;
while (true)
{
try
{
newClient = myListener.AcceptTcpClient();
}
catch
{
//当单击‘停止监听’或者退出此窗体时 AcceptTcpClient() 会产生异常
//因此可以利用此异常退出循环
break;
}
//每接收一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息;
User user = new User(newClient);
Thread threadReceive = new Thread(ReceiveData);
threadReceive.Start(user);
userList.Add(user);
AddItemToListBox(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint));
AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count));
}
}
/// <summary>
/// 处理接收的客户端信息
/// </summary>
/// <param name="userState">客户端信息</param>
private void ReceiveData(object userState)
{
int ac=0;
int pa=0;
User user = (User)userState;
TcpClient client = user.client;
while (isNormalExit == false)
{
string receiveString = null;
try
{
//从网络流中读出字符串,此方法会自动判断字符串长度前缀
receiveString = user.br.ReadString();
}
catch (Exception)
{
if (isNormalExit == false)
{
AddItemToListBox(string.Format("与[{0}]失去联系,已终止接收该用户信息", client.Client.RemoteEndPoint));
RemoveUser(user);
}
break;
}
AddItemToListBox(string.Format("来自[{0}]:{1}",user.client.Client.RemoteEndPoint,receiveString));
string[] splitString = receiveString.Split(',');
if (splitString[0] == "~")
{
string[] AcAndPa = splitString[1].Split('+');
ac = int.Parse(AcAndPa[0]); //账号
pa = int.Parse(AcAndPa[1]); //密码
}
switch(splitString[0])
{
case "Login": //上线
//user.userName = splitString[1];
SendToAllClient(user,receiveString);
break;
case "Logout": //下线
SendToAllClient(user,receiveString);
RemoveUser(user);
return;
case "Talk": //传递聊天信息
string talkString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2);
AddItemToListBox(string.Format("{0}对{1}说:{2}",user.userName,splitString[1],talkString));
SendToClient(user,"talk," + user.userName + "," + talkString);
foreach(User target in userList)
{
if(target.userName == splitString[1] && user.userName != splitString[1])
{
SendToClient(target,"talk," + user.userName + "," + talkString);
break;
}
}
break;
case "~": //登陆,验证账号密码
int ac1, pa1,le;
bool aaa = true;
le = GetRows("AcAndPa.txt");
FileStream fs = new FileStream("AcAndPa.txt", FileMode.Open); //账号密码表
StreamReader sr = new StreamReader(fs);
string path;
string AcAndPa1;
AcAndPa1= sr.ReadLine();
ac1 = int.Parse(AcAndPa1.Split(':')[0]);
pa1 = int.Parse(AcAndPa1.Split(':')[1]);
for(int i=1;i<le;i++)
{
if (ac1 == ac && pa1 == pa)
{
path=ac1.ToString()+".txt";
FileStream ff= new FileStream(path, FileMode.Open);
StreamReader ss = new StreamReader(ff);
user.userName = ss.ReadLine();
user.bw.Write("ok," + user.userName);
user.bw.Flush();
ss.Close();
ff.Close();
aaa = false;
break;
}
else
{
AcAndPa1 = sr.ReadLine();
ac1 = int.Parse(AcAndPa1.Split(':')[0]);
pa1 = int.Parse(AcAndPa1.Split(':')[1]);
}
}
if (aaa == true)
{
user.bw.Write("no");
user.bw.Flush();
RemoveUser(user);
isNormalExit = true;
//user.Close();
//AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count));
}
sr.Close();
fs.Close();
break;
default:
AddItemToListBox("什么意思啊:" + receiveString);
break;
}
}
}
private int GetRows(string FilePath)
{
int l;
using (StreamReader read = new StreamReader(FilePath, Encoding.Default))
{
l=read.ReadToEnd().Split('\n').Length;
return l;
}
}