代码:
(服务器端)
byte[] mybyte=new byte[1024];
try
{
                            
//get ip address
IPAddress ipaddr=IPAddress.Parse(ip); IPEndPoint localend=new IPEndPoint(ipaddr,int.Parse(port));
slistener=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //bind socket
slistener.Bind(localend);

//start listening
slistener.Listen(10); while(true)
            {
if(handler==null)
{
slistener.BeginAccept(new AsyncCallback(Acceptcallback),slistener);
socketevent.WaitOne();


}
else
{
socketevent.Reset();
handler.BeginReceive(buffer,0,buffer.Length,0,new AsyncCallback(ReceiveCallback),handler);
socketevent.WaitOne(); }



}
}
catch(SocketException my)
{
MessageBox.Show(my.Message.ToString(),"error",System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Hand); }

解决方案 »

  1.   

    (客户端)
    string data=this.richTextBox1.Text.Trim();
    string a=data+"<the end>";
    byte []bytedata=System.Text.Encoding.Default.GetBytes(a);

    ////////////
    try
    {
    if(!sclient.Connected)
    {
    sclient.BeginConnect(endpoint,new AsyncCallback(this.connectcallback),sclient);
    socketdone.WaitOne();//阻塞线程
    MessageBox.Show("connect is ok!");
    }


    //send data
    sclient.BeginSend(bytedata,0,bytedata.Length,0,new AsyncCallback(this.sendcallback),sclient);
    socketdone.WaitOne();//阻塞线程

    //receive
    sclient.BeginReceive(buffer,0,buffer.Length,0,new AsyncCallback(this.receivecallback),sclient);
    socketdone.WaitOne();//阻塞线程
    sclient.Shutdown(SocketShutdown.Both);
    sclient.Close();

    }
    catch(Exception my)
    {
                   socketdone.Reset();
    return; }
                
    }
    public void connectcallback(IAsyncResult ar)
    {
    try
    {
    Socket sclient=(Socket)ar.AsyncState;
    sclient.EndConnect(ar);
    socketdone.Set();
    }
    catch(Exception my)
    {
                        MessageBox.Show(my.Message.ToString(),"connectcallback(client)");
       return; }

    } public void sendcallback(IAsyncResult ar)
    {
    try
    {
    Socket sclient=(Socket)ar.AsyncState;
    int bytesend=sclient.EndSend(ar);

    socketdone.Set();
    }
    catch(Exception my)
    {
    MessageBox.Show(my.Message.ToString(),"sendcallback(client)");
                           return;
    }
    } public void receivecallback(IAsyncResult ar)
    {
    try
    {
    Socket sclient=(Socket)ar.AsyncState;

    int bytereceive=sclient.EndReceive(ar);
      

    box+=System.Text.Encoding.Default.GetString(buffer,0,bytereceive);

    MessageBox.Show(box);
    socketdone.Set();
    }

    catch(Exception my)
    {
    MessageBox.Show(my.Message.ToString(),"receivecallback(client)");
    return; }