2012-03-03 72 views
3

來自Android 2.2手機的Java Android應用程序正在向C#程序發送字符串數據。接收數據並正確顯示的C#程序第一次只有。然後它不停止接收數據。但是由於沒有數據,在調試時並沒有接收到由Java App第二次發送的數據,因此它顯示爲0作爲收到的數據。TCP Socket不停止接收C#程序中的數據

首先我想,可能是Java應用程序不斷髮送數據。但即使Java應用程序已關閉,C#程序仍在接收數據。 C#程序的

完整的源代碼是在下面:

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Linq; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
using System.Windows.Forms; 

namespace Network_IM 
{ 
    public partial class Server : Form 
    { 
     public Socket listnerSocket; 
     public Socket workerSocket; 
     public AsyncCallback workerAsyncCallBack; 

     //As a Client 
     Socket clientSocket; 

     public Server() 
     { 
      InitializeComponent(); 
      OnLoad(); 
      RegisterEvents(); 
     } 

     private void RegisterEvents() 
     { 
      button1.Click += new EventHandler(button1_Click); 
      txtInput.KeyDown += new KeyEventHandler(txtInput_KeyDown); 
     } 

     void txtInput_KeyDown(object sender, KeyEventArgs e) 
     { 
      if(e.KeyCode == Keys.Enter) 
       button1_Click(null, null); 
     } 

     void button1_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       clientSocket = new Socket(AddressFamily.InterNetwork, 

SocketType.Stream, ProtocolType.Tcp); 
       clientSocket.Connect(IPAddress.Parse("192.168.1.5"), 8222); 
       clientSocket.Send(Encoding.UTF8.GetBytes(txtInput.Text)); 
       clientSocket.Close(); 
       txtLog.Text += " | Me: " + txtInput.Text + " | "; 
       txtInput.Clear(); 
       txtInput.Focus(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void OnLoad() 
     { 
      try 
      { 
       IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8221); 
       listnerSocket = new Socket(AddressFamily.InterNetwork, 

SocketType.Stream, ProtocolType.Tcp); 
       listnerSocket.Bind(ipLocal); 
       listnerSocket.Listen(4); 
       listnerSocket.BeginAccept(new AsyncCallback(OnClientConnect), 

null); 
      } 
      catch (SocketException se) 
      { 
       MessageBox.Show(se.Message); 
      } 
     } 

     public void OnClientConnect(IAsyncResult asyn) 
     { 
      try 
      { 
       workerSocket = listnerSocket.EndAccept(asyn); 
       WaitForData(workerSocket); 
      } 
      catch (ObjectDisposedException) 
      { 
       Debugger.Log(0, "1", "\n OnClientConnection: Socket has been 

closed\n"); 
      } 
      catch (SocketException se) 
      { 
       MessageBox.Show(se.Message); 
      } 
     } 

     private void WaitForData(Socket workerSoc) 
     { 
      try 
      { 
       if (workerAsyncCallBack == null) 
        workerAsyncCallBack = new AsyncCallback(OnDataReceived); 
       CSocketPacket theSocPkt = new CSocketPacket(); 
       theSocPkt.thisSocket = workerSoc; 
       workerSoc.BeginReceive(theSocPkt.dataBuffer, 0, 

theSocPkt.dataBuffer.Length, SocketFlags.None, workerAsyncCallBack, theSocPkt); 
      } 
      catch (SocketException se) 
      { 
       MessageBox.Show(se.Message); 
      } 
     } 

     public void OnDataReceived(IAsyncResult asyn) 
     { 
      try 
      { 
       CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState; 
       int iRx = theSockId.thisSocket.EndReceive(asyn); 
       char[] chars = new char[iRx + 1]; 
       Encoding.UTF8.GetDecoder().GetChars(theSockId.dataBuffer, 0, iRx, 

chars, 0); 
       String szData = new String(chars); 
       setTxtLogText(szData); 
       WaitForData(workerSocket); 
      } 
      catch (ObjectDisposedException) 
      { 
       Debugger.Log(0, "1", "\nOnDataReceived: Socket has been 

closed\n"); 
      } 
      catch (SocketException se) 
      { 
       MessageBox.Show(se.Message); 
      } 
     } 

     delegate void setTxtLogTextDelegate(string newText); 

     private void setTxtLogText(string newText) 
     { 
      try 
      { 
       if (txtLog.InvokeRequired) 
       { 
        setTxtLogTextDelegate txtLogDelegate = new 

setTxtLogTextDelegate(setTxtLogText); 
        if (newText != "\0") 
         txtLog.Invoke(txtLogDelegate, new object[] { newText }); 
       } 
       else 
        txtLog.Text += newText.Remove(1); 
      } 
      catch (Exception ex) 
      { throw ex; } 
     } 
    } 

    public class CSocketPacket 
    { 
     public Socket thisSocket; 
     public byte[] dataBuffer = new byte[1]; 
    } 
} 

我變得瘋狂通過源代碼一遍又一遍去。請幫幫我。 :)

回答

2

如果你得到的東西是非正面的,這意味着「結束」。這是你的工作來檢查這種情況,並停止請求數據(實際上,可能會關閉你的端口套接字)。

即使您稱之爲700次,它也會返回非正值,這是正確的。所以...不要這樣做。只要你gt iRx < = 0,停止詢問數據

作爲一個額外的注意,你的解碼代碼是不健壯的;不能保證UTF-8每個字節只有一個字符,因此假設字符充滿數據是不安全的。您應該捕獲GetChars的返回值,並在字符串構造函數中使用它來限制您查看的字符。或者更簡單:只需使用Encoding.Utf8.GetString(...)

+0

感謝@Marc,它工作。我是如何轉儲的。我甚至不能簡單地這樣想。我也在[CodeProject]上發佈了這個問題(http://www.codeproject.com/Questions/339610/TCP-Socket-is-not-stopping-receiving-data-in-Cshar)。 [在這裏回答](http://www.codeproject.com/Answers/339849/TCP-Socket-is-not-stopping-receiving-data-in-Cshar)也非常幫助我。 非常感謝。 – Krish 2012-03-05 11:25:25