public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label = (text, la) =>
{
la.Text = text;
};
slist = aa =>
{
listBox1.Items.Add(aa);
};
}
private int serverPort = 6666;
public byte[] dataBuffer = new byte[10000000];
private Socket client;
private delegate void setLabel(string text, Label la);
private setLabel label;
private delegate void SetListBoxCallBack(string str);
private SetListBoxCallBack slist;
private void button1_Click(object sender, EventArgs e)
{
ServerConnection();
}
//连接服务器
private void ServerConnection()
{
try
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("10.100.3.160"), serverPort);
client = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
client.Connect(ipEndPoint);
label1.Invoke(label, client.RemoteEndPoint.ToString(), label1);
label2.Invoke(label, client.LocalEndPoint.ToString(), label2);
client.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), client);
}
catch (Exception ex)
{
throw;
}
}
//回调接收函数
private void RecieveCallBack(IAsyncResult iar)
{
Socket socketData = (Socket)iar.AsyncState;
int iRx = socketData.EndReceive(iar);
string revStr = System.Text.Encoding.Default.GetString(dataBuffer, 0, iRx);
string[] str = revStr.Split('|');
if (str[0] == "PID")
{
serverPort = Convert.ToInt32(str[1]);
ServerConnection();
}
if (str[0] == "mesg")
{
listBox1.Invoke(slist, str[1]);
socketData.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), socketData);
}
}
}