目前在做一個程序,安卓手機每一秒鐘向PC機發送若干條數據,有可能一台機器發,也有可能若干台同時發,PC機用C#接收數據。我測試了一台安卓發數據可以正常接收,可是當若干台同時發數據的時候,就出現問題了。後來我發現不知道為什麼,這些安卓設備的IP地址用DHCP自動獲取IP的時候IP都是一樣的,我想會不會就是因為兩個相同IP的機器發送數據的時候,因為後來發後數據的機器會把原先正在發送的機器建立的TCP通信鏈接給關掉然後自己在發送數據,現在由於實驗室路由器比較特殊,我沒有權限改成靜態獲取,所以在此問一下是不是因為這個原因出的錯,下面列出代碼,麻煩大家幫忙看一看,出錯的地方我用注釋標記出來了
安卓端發送數據代碼
public void sendToPC(String data){
try {
s =new Socket("192.168.0.104",8730);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dout=null;
try
{
dout =new DataOutputStream(s.getOutputStream());
Thread.sleep(50, 0);
dout.writeBytes(data);
dout.flush();
}catch(Exception e){
}
}
C#段代碼
private void listenConnect()
{
while (true)
{
tcpClient = myListener.AcceptTcpClient();
//獲取網絡流
User user = new User(tcpClient);
Thread receiveThread = new Thread(receiveData);
receiveThread.IsBackground = true;
receiveThread.Start(user);
}
}
string receiveString = "";
public void receiveData(object u)
{
User user = (User)u;
NetworkStream netStream1 = user.client.GetStream();
while(true){
byte[] myReadBuffer = new Byte[1024];
int numberOfBytesRead = 0;
StringBuilder myCompleteMessage = new StringBuilder();
int nodeId = 0;
do
{
numberOfBytesRead = netStream1.Read(myReadBuffer, 0, myReadBuffer.Length);//出錯總是在這一句,提示錯誤“遠程主機主動關閉現有連接”
myCompleteMessage.AppendFormat("{0}", Encoding.UTF8.GetString(myReadBuffer, 0, numberOfBytesRead));
} while (netStream1.DataAvailable);
receiveString = myCompleteMessage.ToString();
string[] receivearr = receiveString.Split('!');
for (int i = 0; i < receivearr.Length-1;i++ )
{
string[] infoarr = receivearr[i].Split('#');
DoWork(infoarr[1], infoarr[0]);
}
}
}
}
我最近也在做相關的項目,2台android手機跟PC通訊都很正 常。如果需要我可以給你個DEMO程序參照。