简体   繁体   English

使用套接字编程将数据从Java发送到C.

[英]Sending data from Java to C using socket programming

i am making a program that sends a string from a Java client to a C server using WinSock2. 我正在创建一个程序,使用WinSock2将字符串从Java客户端发送到C服务器。 I am using DataOutputStream to send the data through the socket. 我正在使用DataOutputStream通过套接字发送数据。

The C server, acknowledges the bytes received, but when i try accessing the data, nothing is displayed. C服务器确认收到的字节,但是当我尝试访问数据时,不会显示任何内容。

SERVER 服务器

Socket socket = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;
 try {
  socket = new Socket("10.40.0.86", 2007);
  dataOutputStream = new DataOutputStream(socket.getOutputStream());
  dataInputStream = new DataInputStream(socket.getInputStream());
  //dataOutputStream.writeUTF("How are you doing let us see what is the maximum possible length that can be supported by the protocal");
  String line = "hey";
  dataOutputStream.writeUTF(line);
  dataOutputStream.flush();

  //System.out.println(dataInputStream.readLine());
  System.out.println((String)dataInputStream.readLine().replaceAll("[^0-9]",""));
  //System.out.println(dataInputStream.readInt());
  //System.out.println(dataInputStream.readUTF());
 } catch (UnknownHostException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

CLIENT 客户

if (socket_type != SOCK_DGRAM)
            {
                retval = recv(msgsock, Buffer, sizeof(Buffer), 0);
                printf("Server: Received datagram from %s\n", inet_ntoa(from.sin_addr));

            }

output 产量

Server: Received 5 bytes, data "" from client
BUFFER :
Server: Echoing the same data back to client...
BUFFER :
Server: send() is OK.

您的C代码需要理解writeUTF()编写的数据格式(请参阅Javadoc),否则更简单的是您需要在Java端使用write(char [])或write(byte [])。

Here is how I solved this :-) 这是我如何解决这个问题:-)

dataOutputStream.write(line.getBytes());

Or to be more specific here is my code: 或者更具体的是这里是我的代码:

out.write(("Hello from " + client.getLocalSocketAddress()).getBytes());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM