日期:2014-05-20  浏览次数:20840 次

线程问题

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ServerProject
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }

  IPAddress myIP = IPAddress.Parse("127.0.0.1");
  IPEndPoint myServer;
  Socket sock;
  bool check = true;
  Socket accSock;

  private void button1_Click(object sender, EventArgs e)
  {
  try
  {
  myIP = IPAddress.Parse(this.textBox1.Text);
  }
  catch (Exception)
  {

  MessageBox.Show("你的IP格式不正确,请重新输入!");
  return;
  }
  try
  {
  Thread thread = new Thread(new ThreadStart(accp));
  thread.Start();
  }
  catch (Exception ex)
  {

  this.textBox3.AppendText(ex.Message);
  }
  }

  private void accp()
  { 
  int port=int.Parse(this.textBox2.Text);
  myServer = new IPEndPoint(myIP, port);
  sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  sock.Bind(myServer);
  sock.Listen(50);
  this.textBox3.AppendText("主机:"+this.textBox1.Text+" 端口:"+this.textBox2.Text+" 开始监听..\r\n");
  accSock = sock.Accept();
  if (accSock.Connected)
  {
  this.textBox3.AppendText("与客户建立连接\r\n");
  while (check)
  {
  Byte[] rec=new Byte[64];
  NetworkStream netStream = new NetworkStream(accSock);
  netStream.Read(rec, 0, rec.Length);
  string recMsg = System.Text.Encoding.BigEndianUnicode.GetString(rec);
  richTextBox1.AppendText(recMsg+"\r\n");
  }
  }

  }

  private void button2_Click(object sender, EventArgs e)
  {
  try
  {
  Byte[] sendByte=new Byte[64];
  string strSend = this.textBox3.Text;
  sendByte = System.Text.Encoding.BigEndianUnicode.GetBytes(strSend.ToCharArray());
  NetworkStream netStream = new NetworkStream(accSock);
  netStream.Write(sendByte, 0, sendByte.Length);
  }
  catch (Exception)
  {
   
  MessageBox.Show("连接尚未建立,无法发送");
  }
  }

  private void button3_Click(object sender, EventArgs e)
  {
  try
  {
  sock.Close();
  this.textBox3.AppendText("主机:" + this.textBox1.Text + " 端口:" + this.textBox2.Text + " 开始监听..\r\n");
  }
  catch (Exception)
  {