套接字写不正常c#

时间:2013-08-22 14:02:52

标签: c# sockets

我正在使用我的C#应用​​程序开发生物识别系统。 Sdk通过端口2100上的TCP / IP提供连接,并通过接收和发送字符串进行通信。

我的课程:

class Biometry
{
    private System.Net.Sockets.TcpClient _clientSocket = new System.Net.Sockets.TcpClient();

    public Biometry() {
        //connect to socket
        _clientSocket.Connect("127.0.0.1", 2100);
        _clientSocket.ReceiveTimeout = 9000;
    }

    public String identify(String msg) {
        //get network stream
        NetworkStream _serverStream = _clientSocket.GetStream();

        //send an array of bites that represents a string(encoded)
        System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(msg);
        _serverStream.Write(outStream, 0, outStream.Length);


        //reads the response from networkStream
        byte[] inStream = new byte[10025];
        _serverStream.Read(inStream, 0, (int)_clientSocket.ReceiveBufferSize);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream);

        _serverStream.Close();
        return returndata;

    }
}

问题是: 它不工作!!生物统计仅在我关闭应用程序(连接已关闭)时有效(SDK只能理解我的请求)。

1 个答案:

答案 0 :(得分:0)

您可能需要在开始阅读之前使用_serverStream.Flush()刷新流。

另一个问题可能是在你的问题中你说你需要连接到端口21000,但在你的代码中你连接到2100,这可能是两个地方的拼写错误,但应该修复; - )


除了刷新流,您的服务器可能还在等待“消息结束”指示符?