读书人

socket唯其如此收到一次数据第二次就

发布时间: 2013-07-11 15:38:46 作者: rapoo

socket只能收到一次数据,第二次就没有反应了。求指导!!


namespace test3{

using System;
using System .Net .Sockets ;
using System .Net ;
using System .Text ;
using System .Threading ;
using System.Collections;
using System .IO ;
using UnityEngine;

public class Socketfz
{
public static Socket soc =null ;
private static Thread nthread = null;
private static Thread thread = null;
//private static byte[] buffer = new byte[1024];
//private static byte[] buf = new byte[1024];
public static string data ;
public static string cd;
public static string dingwei;
public static string speed;
public static string angle;
public static string fx;


public Socketfz ()
{
}

public void SocketConnection(int Lport){


soc = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint (IPAddress.Any, Lport);

soc.Bind (ipep);
soc.Listen (10);

thread = new Thread (new ThreadStart (ListenC));
thread .Start ();
}
static void ListenC(){

while(true){
try{
Socket s = soc.Accept();//监听
s.Send(Encoding.ASCII.GetBytes("success!"));
nthread = new Thread(Redata);
nthread.Start(s);

}catch(Exception e ){
MonoBehaviour .print (e.ToString());

}
}
}

static void Redata(object socket){
Socket socket1 = (Socket)socket;
byte[] b2 = new byte[19];
int len = 0;
while (true) {
try{
int r = socket1.Receive( b2 , len , b2.Length - len ,0);
if(r == 0){
break ;
}
len += r;
if(len < 19)
continue ;
if(b2[0]==0xFF & b2[1]== 0xFF& b2[2]==0xFF){//判断数据头
dingwei = b2[5].ToString("X2") + b2[4].ToString("X2") + b2[3].ToString("X2") ;
speed = b2[6].ToString("X2");


angle = b2[8].ToString("X2")+ b2[7].ToString("X2");
fx = b2[9].ToString("X2");

MonoBehaviour .print (dingwei +" " +speed +" " +angle +" "+fx);
}
}catch (Exception e){
MonoBehaviour .print (e.ToString());
//sw.Close();
//sw.Dispose();
//socket1 .Shutdown(SocketShutdown.Both);
//socket1 .Close();
break;
}
}
}
}
}




发送的数据 是byte[19]的数据 数据开头是FFFFFF ,不知道为什么,只能接到第一个数据,然后就收不到数据了。。。。。求大神指导啊!!!!~!!!!
粘包拉,出异常拉。
[解决办法]
你断点调试的时候是在哪个地方卡住的?有没有看输出的值到哪里出错了?
[解决办法]
数据先别判断,把收到的先都显出来,看有吗?
[解决办法]
引用:
Quote: 引用:

debug了一下 ,发现到了

if(r == 0){
break ;
}


第二次 break以后 while循环就停止了。。。

byte[] b2 = new byte[19];长度只有那么长只有19你第一次读的时候就读完19了,下次读估计没有数据读不了

我说的是你传进来的参数
[解决办法]

while (true) {
try{
int r = socket1.Receive( b2 , 0 , b2.Length ,0);
if(r == 0){
continue ;
}
//len += r;
//if(len < 19)
//continue ;
if(b2[0]==0xFF & b2[1]== 0xFF& b2[2]==0xFF){

dingwei = b2[5].ToString("X2") + b2[4].ToString("X2") + b2[3].ToString("X2") ;
speed = b2[6].ToString("X2");


angle = b2[8].ToString("X2")+ b2[7].ToString("X2");
fx = b2[9].ToString("X2");

MonoBehaviour .print (dingwei +" " +speed +" " +angle +" "+fx);
}
}catch (Exception e){
MonoBehaviour .print (e.ToString());
//sw.Close();
//sw.Dispose();
socket1 .Shutdown(SocketShutdown.Both);
socket1 .Close();
break;
}

读书人网 >C#

热点推荐