.NET里面用System.Net.Sockets.Socket
并且用法不一样,不要这样照搬

解决方案 »

  1.   

    C#寫的簡單的FTP服務端。
    private void btnStart_Click(object sender, System.EventArgs e)
    {

    try
    {
    port=Int32.Parse(textBox1.Text);
    }
    catch
    {
    MessageBox.Show("Port number wrong!");
    } try
    {
    listener=new TcpListener(port);
    listener.Start();
    statusBar1.Text="Service started!";
    Thread thread=new Thread(new ThreadStart(recevive));
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    private void recevive()
    {
    sock=listener.AcceptSocket();
    if(sock.Connected)
    {
    statusBar1.Text="Connect succeed!";
    string str=richTextBox1.Text;
    byte[] bytee=System.Text.Encoding.BigEndianUnicode.GetBytes(str.ToCharArray());
    sock.Send(bytee,bytee.Length,0); while(!control)
    {
    NetworkStream stream=new NetworkStream(sock);
    byte[] by=new byte[1024];
    int i=sock.Receive(by,by.Length,0);
    string ss=System.Text.Encoding.BigEndianUnicode.GetString(by); richTextBox2.AppendText(ss);
    j=richTextBox2.Lines.Length;

    if(j>=2)
    {
    if(richTextBox2.Lines[j-2].ToString()!="@@@@@@")
    {
    filestream=new FileStream(richTextBox2.Lines[j-2].ToString(),FileMode.Open,FileAccess.Read); byte[] bb=new byte[1024];

    while((number=filestream.Read(bb,0,1024))!=0)
    {
    stream.Write(bb,0,number);
    stream.Flush();
    } string st="<EOF>";
    byte[] byt=new byte[1024];
    byt=System.Text.Encoding.ASCII.GetBytes(st.ToCharArray()); sock.Send(byt,byt.Length,0);
    filestream.Close();
    }
    else if(richTextBox2.Lines[j-2].ToString()=="@@@@@@")
    {
    control=true;
    }
    }
    }
    } } private void btnExit_Click(object sender, System.EventArgs e)
    {
    Application.Exit();
    } private void btnStop_Click(object sender, System.EventArgs e)
    {
    try
    {
    control=true;
    listener.Stop();
    statusBar1.Text="Service stop!";
    }
    catch
    {
    MessageBox.Show("Service not start!");
    }
    }
      

  2.   

    用connected属性似乎不妥!因为该属性反映的socket上次操作连接状态!
      

  3.   

    dxjhq(毅楊) 的方法不能判断对方终止或线路断开的情况
    krank(Alex.Young) 说得对,connected属性是不实时的
    有好的办法的朋友来发表一下看法!!!