我正在制作一个能够远程控制相机(Scopia XT5000 - Radvision)等设备的应用程序。我需要向设备发送初始化命令,以便能够发送将控制设备的AT命令。
我发送初始化命令后,服务器应该回复:
字符串
?? \ 0 \ 0 \ 0 AT [< IP400C9XT5000-03.01.00.0028 \ r ?? \ 0 \ 0 \ 0OK \ r
字节
170 170 0 0 0 32 65 84 91 60 73 80 52 48 48 67 57 88 84 53 48 48 48 45 48 51 46 48 49 46 48 48 46 48 48 50 56 13 170 170 0 0 0 3 79 75 13
当我在这里休息时,我尝试调试并获得这些值
serverStream.Read(inStream,0,inStream.Length);
但每次我在没有调试或休息的情况下运行程序时,它会给我不同的字符串和字节。就像这样 字符串
?? \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0
字节
170 170 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
可能是什么问题?
是吗:
- 空字节?
- 回车? “\ r”?
- 多行?
整个代码:
{
TcpClient clientSocket = new System.Net.Sockets.TcpClient();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
}
public void openSocket()
{
if (clientSocket.Connected)
{
clientSocket.Close();
}
clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("10.0.3.202", 55003);
label1.Text = "Client Socket Program - Server Connected ...";
}
private void btnSend_Click(object sender, EventArgs e)
{
openSocket();
//header bytes and initAT bytes are the initialization command for me to send AT commands
msg("Init: ");
NetworkStream serverStream = clientSocket.GetStream();
//header bytes to enable AT command
byte[] header = {170,170,0,0,0,8 };
serverStream.Write(header, 0, header.Length);
serverStream.Flush();
//Initialize the Interface
byte[] initAT = System.Text.Encoding.ASCII.GetBytes("AT[&IPV\r");
serverStream.Write(initAT,0, initAT.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, inStream.Length);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}
private void btnRight_Click(object sender, EventArgs e)
{
msg("Right : ");
NetworkStream serverStream = clientSocket.GetStream();
//AT Command to move the main camera to right
byte[] outStream3 = System.Text.Encoding.ASCII.GetBytes("AT[&SY011R\r");
serverStream.Write(outStream3, 0, outStream3.Length);
byte[] inStream2 = new byte[48];
serverStream.Read(inStream2, 0,inStream2.Length);
string returndata = System.Text.Encoding.ASCII.GetString(inStream2);
msg(returndata);
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
}
答案 0 :(得分:0)
Read
返回读取的字节数。您有一个10025字节的缓冲区,但在Read
之后它没有填满。您可能希望循环,直到读取所需的所有字节。
调试时有效,因为花费了额外的时间,网络流有时间完全接收结果,所以当调用Read
时,所有数据都可用并放入缓冲区。 / p>
参考:http://msdn.microsoft.com/en-gb/library/system.io.stream.read.aspx