我要编一个跟qq差不多的程序,老师编的代码我看不懂,请前辈们帮我做一下注释什么的,谢谢!
这是服务器端的代码:using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using
using
using System.Threading;
using System.Collections;
namespace tcpS
{
public partial class Form1 : Form
{
Hashtable onLineUsers;
TcpListener listener;
Thread listenThread;
DoTrans dotrans;
public Form1()
{
InitializeComponent();
onLineUsers = new Hashtable();
listener = new TcpListener(6666);
listenThread =
new Thread(new ThreadStart(listen));
dotrans = new DoTrans();
}
/// <summary>
/// 监听6666端口,接受所有客户端程序的链接请求
/// 建立通信信道
/// </summary>
private void listen()
{
listener.Start();//开始监听6666,看有人连我么
while (true)
{
TcpClient client = listener.AcceptTcpClient();//阻塞
//service(client);
Thread serviceT =
new Thread(new ParameterizedThreadStart(service));
serviceT.Start(client);
}
}
/// <summary>
/// 为C提供它所要求的服务
/// </summary>
/// <param name="C"></param>
private void service(object bj)
{
TcpClient C = bj as TcpClient;
NetworkStream ns = C.GetStream();
byte[] mss=new byte[1024];
byte[] replay;
while (true)
{
ns.Read(mss, 0, 1024);
string message =Encoding.UTF8.GetString(mss);
string[] ms = message.Split(new char[] { '^'});
switch (ms[0])
{
case "login"://login^zjl^123^
DataTable dt = dotrans.SelTran("select * from t_user where userid='"+ms[1]+"'");
if(dt==null||dt.Rows.Count==0)
{//无此用户
replay =Encoding.UTF8.GetBytes("login^nouser^");
}
else
{
if (dt.Rows[0]["password"].ToString() == ms[2])
{//登录成功
replay = Encoding.UTF8.GetBytes("login^ok^");
onLineUsers.Add(ms[1], C);
}
else
{//密码错误
replay = Encoding.UTF8.GetBytes("login^pwdWrong^");
}
}
ns.Write(replay, 0, replay.Length);
ns.Flush();
break;
case "chat"://chat^zjl^awg^safsa^
TcpClient tempTC = onLineUsers[ms[2]] as TcpClient;
NetworkStream tempNS=tempTC.GetStream();
ns.Write(mss,0,mss.Length);
break;
case "quit":
onLineUsers.Remove(ms[1]);
break;
case "adduser"://adduser^zjl^123^张飞^
if (dotrans.DoTran("insert into t_user values('"+ms[1]+"','"+ms[3]+"','"+ms[2]+"')"))
{
replay = Encoding.UTF8.GetBytes("adduser^ok^");
}
else
{
replay = Encoding.UTF8.GetBytes("adduser^error^");
}
ns.Write(replay, 0, replay.Length);
ns.Flush();
break;
case "refreshU"://UserList^zjl^awg^zj^zxm^....
//onLineUsers的key:所有在线用户的编号
string replayStr = "UserList^";
foreach (object obj in onLineUsers.Keys)
{
replayStr += obj.ToString() + "^";
}
replay = Encoding.UTF8.GetBytes(replayStr);
ns.Write(replay, 0, replay.Length);
ns.Flush();
break;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
listenThread.Start();
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}