用于本地Java服务的客户端

时间:2013-02-26 13:19:47

标签: c# java sockets client tcpclient

我正在尝试将我的C#应用​​程序与基于Java的本地服务连接起来。我无法访问Java代码和服务详细信息,我唯一知道的是通过套接字通过指定端口进行通信。

问题是我可以连接但是不能发送/接收任何数据。我的C#客户端代码如下;

=====================

IPHostEntry ipAddress = Dns.GetHostEntry("127.0.0.1");
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipAddress.AddressList[0].ToString()), 8888);
socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ip);

Encoding ASCII = Encoding.ASCII;
Byte[] byteGetString = ASCII.GetBytes("Service_Command_Message");
Byte[] receivedBytes = new Byte[256];
string l_Response = string.Empty;

socket.Send(byteGetString, byteGetString.Length, SocketFlags.None);

//debugger gets lost at this line. I also tried stream.read    
Int32 bytes = socket.Receive(receivedBytes, receivedBytes.Length, SocketFlags.None);
l_Response += ASCII.GetString(receivedBytes, 0, bytes);
while (bytes > 0)
{
    bytes = socket.Receive(receivedBytes, receivedBytes.Length, SocketFlags.None);
    l_Response = l_Response + ASCII.GetString(receivedBytes, 0, bytes);
}
socket.Close();

=====================

我尝试使用一些端口捕获工具,它显示连接但传输数据的长度显示为0.

感谢您的帮助。

=======更新(使用TcpClinet发送)==========

client = new TcpClient("127.0.0.1", 8888);
stream = client.GetStream();

Byte[] data = System.Text.Encoding.ASCII.GetBytes("Service_Command_Message");

StreamWriter sw = new StreamWriter(stream);

sw.WriteLine(p_Message);
sw.Flush();

========================================

我使用了Flush(),但在关闭应用程序之前,数据仍未传输。

1 个答案:

答案 0 :(得分:0)

由于你的代码遇到了receive方法,我假设send方法没有任何问题。您应该查看SocketError的out参数来验证这一点。

首先,您不能依赖套接字发送或接收所有数据。您发送的字节总是比客户期望的更多。 Socket.Send方法返回发送的字节数,因此您可以使用它来确定是否已发送所有字节:

Byte[] byteGetString = ASCII.GetBytes("Service_Command_Message");
int count = 0;
while (count < byteGetString.Length ) 
{
    count += socket.Send(
        bytes,
        count, 
        bytes.Length - count, 
        SocketFlags.None)
}

你的接收方法挂起的原因可能是因为你的while循环条件:

while (bytes > 0) {
    bytes = socket.Receive(receivedBytes, receivedBytes.Length, SocketFlags.None);
    l_Response = l_Response + ASCII.GetString(receivedBytes, 0, bytes); }

您假设当您收到零长度字节时,您已完成接收,但情况可能并非如此。当您在最后一个循环上填充缓冲区中的某些字节时,可能已到达网络流的末尾。因此,您必须更改while循环条件,如下所示:

while (bytes == receivedBytes.Length) {
    bytes = socket.Receive(receivedBytes, receivedBytes.Length, SocketFlags.None);
    l_Response = l_Response + ASCII.GetString(receivedBytes, 0, bytes); }

如果所有这些都失败了,那么服务器可能没有正确发送/接收字节的可能性。

最后,请务必处理SocketException,因为可以随时删除连接。