C#写的网络游戏猜拳
使用系统。集合。泛型;
使用系统。组件模型;
使用系统。数据;
使用系统。绘图;
使用系统。文本;
使用系统。Windows . Forms
使用System.Net;
使用系统。Net . Sockets
使用系统。穿线;命名空间服务器
{
公共分部类表单1:表单
{
私有TcpListener侦听器;
个人分发名单& ltTcpClient & gtclientList
私有线程t;
私有线程t 1;
私有字符串输出;
公共表单1()
{
initialize component();
set controls();
}私有void setControls()
{
clientList =新列表& ltTcpClient & gt();按钮1。Text = " Start
按钮1。Click+= new EventHandler(button 1 _ Click);
按钮2。Text = " Stop
按钮2。Click+= new EventHandler(button 2 _ Click);
}私有void StartServer()
{
IP address IP = new IP address(new byte[]{ 127,0,0,1 });
listener = new TcpListener(ip,8500);
听众。start();
rich textbox 1 . text+= string . format("服务器:{0}端口号:{1}已启动...\n ",ip。ToString(),8500);
}
私有void GetClient()
{
做
{
if (clientList。Count & gt= 2)
{
//clientList。clear();
打破;
}
其他
{
客户列表。添加(侦听器。acceptcpclient());
outTos += string。Format("Player:{0}正在连接\n ",clientList[clientList。count-1]. client . local endpoint);
if (clientList。计数== 2)
{
尝试
{
t1 =新线程(GetMsg);
t1。start();
}
捕捉
{
t1。abort();
}
}
}
}
while(真);
}
私有void GetMsg()
{
做
{
int byteRead = 0;
int bufferSize = 2000
byte[] buffer =新字节[buffer size];network stream stream 1 = client list[0]。GetStream();
byteRead = stream1。Read(buffer,0,buffer size);
字符串msg =编码。Unicode.GetString(buffer,0,byteRead);network stream stream 2 = client list[1]。GetStream();
byteRead = stream2。Read(buffer,0,buffer size);
字符串msg1 =编码。Unicode.GetString(buffer,0,byteRead);如果(msg!=字符串。空& amp& ampmsg1!=字符串。空的)
{
SendMsg(GetAnsower(msg,msg 1));
}
}
while(真);}私有void SendMsg(int win)
{
字符串p1 =字符串。空的;
字符串p2 =字符串。空的;
if (win == 0)
{
p 1 = " tie ";
P2 = "铁";
}
if (win == 1)
{
P1 = "赢了!";
P2 =“迷路了!”;
}
if (win == 2)
{
P1 = "迷路了!";
P2 =“赢了!”;
} network stream stream 1 = client list[0]。GetStream();
byte[] buffer1 =编码。unicode . GetBytes(p 1);
stream1。写(buffer1,0,buffer1。长度);network stream stream 2 = client list[1]。GetStream();
byte[] buffer2 =编码。unicode . GetBytes(p2);
流2。写(缓冲器2,0,缓冲器2。长度);
OutTos += string。Format("发送给玩家1: {0}玩家2: {1} \ n ",P1,P2);
} private int GetAnsower(字符串m1,字符串m2)
{
int win = 0;
If (m1 == "剪刀")
{
If (m2 == "布")win = 1;
If (m2 ==“石头”)win = 2;
If (m2 ==“剪刀”)win = 0;
}
If (m1 == "stone ")
{
If (m2 == "剪刀")win = 1;
If (m2 ==“布”)win = 2;
if(m2 = = " stone ")win = 0;
}
If (m1 == "cloth ")
{
if(m2 = = " stone ")win = 1;
If (m2 ==“剪刀”)win = 2;
If (m2 == "布")win = 0;
}
回赢;
} void button1_Click(对象发送方,EventArgs e)
{
尝试
{
StartServer();
t =新线程(get client);
t.start();
定时器1。start();
}
catch(例外ex)
{
t.abort();
t1。abort();
定时器1。stop();
定时器1。stop();
}
}
void button2_Click(对象发送方,事件参数e)
{
t.abort();
t1。abort();
听众。stop();
定时器1。stop();
MessageBox。Show("服务器宕机了!");
} private void timer1_Tick(对象发送方,EventArgs e)
{
richTextBox1。text+= outTos;
outTos = string。空的;
}
}
}