日期:2014-05-18 浏览次数:21082 次
//客户端
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8
9 using System.Net;
10 using System.Net.Sockets;
11
12 namespace Client
13 {
14 public partial class ClientMain : Form
15 {
16 public ClientMain()
17 {
18 InitializeComponent();
19 }
20
21 private IPEndPoint ServerInfo;
22 private Socket ClientSocket;
23 private Byte[] MsgBuffer;
24 private Byte[] MsgSend;
25
26 private void ClientMain_Load(object sender, EventArgs e)
27 {
28 this.CmdSend.Enabled = false;
29 this.CmdExit.Enabled = false;
30
31 ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
32 MsgBuffer = new Byte[65535];
33 MsgSend = new Byte[65535];
34 CheckForIllegalCrossThreadCalls = false;
35
36 Random TRand=new Random();
37 this.UserName.Text = "用户" + TRand.Next(10000).ToString();
38 }
39
40 private void CmdEnter_Click(object sender, EventArgs e)
41 {
42 ServerInfo = new IPEndPoint(IPAddress.Parse(this.ServerIP.Text), Convert.ToInt32(this.ServerPort.Text));
43
44 try
45 {
46 ClientSocket.Connect(ServerInfo);
47
48 ClientSocket.Send(Encoding.Unicode.GetBytes("用户: " + this.UserName.Text + " 进入系统!\n"));
49
50 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
51
52 this.SysMsg.Text += "登录服务器成功!\n";
53 this.CmdSend.Enabled = true;
54 this.CmdEnter.Enabled = false;
55 this.CmdExit.Enabled = true;
56 }
57 catch
58 {
59 MessageBox.Show("登录服务器失败,请确认服务器是否正常工作!");
60 }
61 }
62
63 private void ReceiveCallBack(IAsyncResult AR)
64 {
65 try
66 {
67 int REnd = ClientSocket.EndReceive(AR);
68 this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));
69 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
70
71 }
72 catch
73 {
74 MessageBox.Show("已经与服务器断开连接!");
75 this.Close();
76 }
77
78 }
79
80 private void CmdSend_Click(object sender, EventArgs e)
81 {
82 MsgSend = Encoding.Unicode.GetBytes(this.UserName.Text + "说:\n" + this.SendMsg.Text + "\n");
83 if (ClientSocket.Connected)
84 {
85 ClientSocket.Send(MsgSend);
86