public partial class MainForm2 : Form
{
Socket clientSocket = null;
public MainForm2()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(IPAddress.Parse(this.textBox_IP.Text), int.Parse(this.textBox_Port.Text));
this.textBox_Log.Text = "连接服务器成功!\r\n" + this.textBox_Log.Text;
}
catch (Exception)
{
this.textBox_Log.Text = "连接服务器出错,请重新连接!\r\n" + this.textBox_Log.Text;
}
ThreadPool.QueueUserWorkItem(clientReceive, clientSocket);
}
private void button_SendMsg_Click(object sender, EventArgs e)
{
if (clientSocket != null && clientSocket.Connected)
{
string str = this.textBox_Msg.Text;
byte[] data = Encoding.Default.GetBytes(str);
clientSocket.Send(data, 0, data.Length, SocketFlags.None);
}
}
private void clientReceive(object o)
{
private void clientReceive(object o)
{
Socket clientSocket = (Socket)o;
while (true)
{
try
{
byte[] date = new byte[1024 * 1024];
int len = clientSocket.Receive(date, 0, date.Length, SocketFlags.None);
if (len <= 0)
{
this.textBox_Log.Text = "服务器端:已断开连接! \r\n" + this.textBox_Log.Text;
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
return;
}
string str = Encoding.Default.GetString(date, 0, len);
this.textBox_Log.Text = "收到服务器端数据:" + str + "\r\n" + this.textBox_Log.Text;
}
catch (Exception)
{
this.textBox_Log.Text = "服务器端:已断开连接!\r\n" + this.textBox_Log.Text;
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
return;
}
}
}
}
}