namespace client
{
public partial class Form3 : Form
{
private Thread _receiveThread = null;
private NetworkStream _nws = null;
private TcpClient clientTcp = null;
private byte[] cmdBuff = new byte[4096];
private int bufLen = 0;
public Form3()
{
InitializeComponent();
}
private void ReceiveMsg()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()), Convert.ToInt32(textBox2.Text.Trim()));
clientTcp = new TcpClient();
try
{
clientTcp.Connect(ipep);
label4.Text = "已连接";
}
catch (SocketException)
{
label4.Text = "服务器异常";
}
while (true)
{
try
{
_nws = clientTcp.GetStream();
bufLen = clientTcp.Available;
_nws.Read(cmdBuff, 0, bufLen);
_nws.Flush();
if (bufLen == 0)
{
continue;
}
DataObject.Packet packet = (DataObject.Packet)Tool.DeserializeBinary(cmdBuff);
richTextBox1.Text = "[" + packet.Name + "]说:" + packet.Say + "\n" + richTextBox1.Text;
}
catch
{
label4.Text = "服务器异常";
continue;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
_receiveThread = new Thread(new ThreadStart(ReceiveMsg));
_receiveThread.Start();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox3.Text.Trim() == "")
return;
if (textBox4.Text.Trim() == "")
return;
try
{
DataObject.Packet packet = new DataObject.Packet() { ID = 1, Name = textBox4.Text.Trim(), Say = textBox3.Text.Trim() };
byte[] data = Tool.SerializeBinary(packet);
_nws.Write(data, 0, data.Length);
_nws.Flush();
}
catch
{
label4.Text = "服务器异常";
}
}
private void button3_Click(object sender, EventArgs e)
{
clientTcp.Close();
label4.Text = "未连接";
}
}
}