|
[code=csharp]namespace AClient
{
public partial class FClient : Form
{
//计算机是如何判断 isExit
private bool isExit = false;
private BinaryReader br;
private BinaryWriter bw;
public FClient()
{
InitializeComponent();
Random r = new Random(~unchecked((int)DateTime.Now.Ticks));
txtUserName.Text = "" + r.Next(0, 600);
}
private delegate void AddStatusDelegate(string message);
private void AddStatus(string message)
{
if (txtStatus.InvokeRequired)
{
AddStatusDelegate d = new AddStatusDelegate(AddStatus);
//下面这句不懂
txtStatus.Invoke(d, new object[] { message });
}
else
{
txtStatus.AppendText(message);
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
AddStatus("开始连接");
}
private void ConnectToServer()
{
TcpClient client=new TcpClient();
IAsyncResult result = client.BeginConnect(Dns.GetHostName(), 51888, null, null);
while (result.IsCompleted == false)
{
Thread.Sleep(100);
AddStatus("稍等");
}
client.EndConnect(result);
AddStatus("连接成功");
NetworkStream netWorkStream = client.GetStream();
br = new BinaryReader(netWorkStream);
bw = new BinaryWriter(netWorkStream);
AsyncSendMessage(txtUserName.Text+"已登陆");
Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
threadReceive.IsBackground = true;
threadReceive.Start();
}
delegate void SendMessageDelegate(string message);
private struct SendMessageStates
{
public SendMessageDelegate d;
public IAsyncResult result;
}
private void AsyncSendMessage(string message)
{
SendMessageDelegate d = new SendMessageDelegate(SendMessage);
IAsyncResult result = d.BeginInvoke(message, null, null);
while (result.IsCompleted == false)
{
if (isExit==true)
{
return;
}
Thread.Sleep(500);
}
SendMessageStates states = new SendMessageStates();
states.d = d;
states.result = result;
Thread t = new Thread(FinishAsyncSendMessage);
t.IsBackground = true;
t.Start(states);
}
private void SendMessage(string message)
{
try
{
bw.Write(message);
bw.Flush();
}
catch
{
AddStatus("发送失败!");
}
}
private void FinishAsyncSendMessage(object obj)
{
SendMessageStates states = (SendMessageStates)obj;
states.d.EndInvoke(states.result);
}
delegate void ReceiveMessageDelegate(out string receiveString);
private void ReceiveData()
{
string receiveString = null;
while (isExit == false)
{
ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage);
IAsyncResult result = d.BeginInvoke(out receiveString, null, null);
while (result.IsCompleted == false)
{
if (isExit)
{
break;
}
}
}
}
}
}[/code]
|
|