C#多线程局部变量同名是不是就被嵌套使用了?
程序代码:
/// <summary> /// 不停的接收服务器发送来的消息 /// </summary> /// <param name="o"></param> void Recive(object o) { try { Socket socketSend = o as Socket; while (true) { byte[] buffer = new byte[1024 * 1024 * 3]; //实际接收到的有效字节数 int r = socketSend.Receive(buffer); if (r == 0) { break; } //发送的文字消息 if (buffer[0] == 0) { string s = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(socketSend.RemoteEndPoint + ":" + s); } if (buffer[0] == 9) { } if (buffer[0] == 1) { SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = @"C:\Users\Administrator.SKY-20181116FAG\Desktop"; sfd.Title = "请选择要保存的文件"; sfd.Filter = "所有文件|*.*"; sfd.ShowDialog(this); string path = sfd.FileName; using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { fsWrite.Write(buffer, 1, r - 1); } MessageBox.Show("保存成功"); } if (buffer[0] == 2) { ZD(); } } } catch { } }
程序代码:
//发送消息 private void btnSend_Click(object sender, EventArgs e) { try { string str = this.txtSendMsg.Text.Trim(); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); List<byte> list = new List<byte>(); list.Add(0); list.AddRange(buffer); //将集合转为数组 byte[] newbuffer = list.ToArray(); //判断所有选中项集合大于0 if (this.lstClient.SelectedItems.Count > 0) { //获取选中的值 string ip = this.lstClient.SelectedItem.ToString(); Console.WriteLine(ip); Console.WriteLine(dicSocket[ip]); dicSocket[ip].Send(newbuffer); } else { MessageBox.Show("未选中listbox集合的值"); } } catch { } }
程序代码:
/// <summary> /// 心跳测试 /// </summary> public void HeartbeatClient() { while (true) { string str = "69"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); List<byte> list = new List<byte>(); list.Add(9); list.AddRange(buffer); //将集合转为数组 byte[] newbuffer = list.ToArray(); for (int i = 0; i < lstClient.Items.Count; i++) { int flag=0; string ip = lstClient.Items[i].ToString();//获得这一列的IPEndPoint信息 if (dicSocket[ip].Connected) { try { flag = dicSocket[ip].Send(newbuffer);//返回的参数是发送到的字节数 } catch {} } if (flag <= 0) { ShowMsg(ip + "已掉线。"); this.lstClient.Items.Remove(ip); } } } }