0

I am trying to connect my C# application with a local service that is based on Java. I dont have access to the Java code and the service details, the only thing I know is to communicate via socket through a specified port.

The problem is I can connect BUT cannot send / receive any data. My C# client code is as follows;

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

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();

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

I tried using some port capture tool, that shows the connectivity but length of transmitted data is shown to be 0.

Thanks for any help.

======= update (using TcpClinet to send) ==========

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();

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

I've used Flush() but still data is not transmitted till I close the application.

4

1 回答 1

0

由于您的代码命中了接收方法,我假设发送方法没有任何问题。您应该查看 out 参数SocketError来验证这一点。

首先,您不能依赖套接字发送或接收所有数据。您发送的字节数总是有可能超出客户的预期。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,因为连接随时都可能掉线。

于 2013-02-27T01:35:25.253 回答