从C套接字客户端读取输入到Java套接字服务器

时间:2015-03-03 10:22:21

标签: java c sockets client

我有2个套接字客户端和2个套接字服务器,其中一个在C和Java中,并且都作为进程在我的本地计算机上运行。

除了C套接字和Java服务器之外,他们都可以成功地相互通信。它们成功连接但是当我输入C客户端时,回车键没有完成消息并以与C服务器通信时相同的方式将其发送到Java服务器。

非常感谢任何见解。

Java Server:

import java.net.*;
import java.io.*;

public class SimpleServer extends Thread
{
   private ServerSocket serverSocket;
   String clientmsg = "";

   public SimpleServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }

    public void run()
    {
        while(true)
        {
            try
            {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("Just connected to " + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thank you for connecting to "
                + server.getLocalSocketAddress() + "\nGoodbye!");
                server.close();
            }

            catch(SocketTimeoutException s)
            {
                System.out.println("Socket timed out!");
                break;
            }

            catch(IOException e)
            {
                e.printStackTrace();
                break;
            }
        }
    }
    public static void main(String [] args)
    {
        int port = Integer.parseInt(args[0]);
        try
        {
            Thread t = new SimpleServer(port);
            t.start();
        }

        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

C客户:

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>

void error(char *msg) 
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sockfd, portno;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    int n;
    char buffer[256];

    if (argc < 3)
    {
        error("ERROR, no port provided");
    }

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sockfd < 0)
    {
        error("ERROR opening socket");
    }

    server = gethostbyname(argv[1]);

    if (server == NULL)
    {
        error("ERROR, host not found\n");
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = atoi(argv[2]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);

    bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);

    if (connect(sockfd,(struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        error("ERROR connecting to server");
    }

    printf("Enter a message for the server: ");

    bzero(buffer,256);
    fgets(buffer,sizeof(buffer),stdin);
    n = write(sockfd,buffer,strlen(buffer));

    if (n < 0)
    {/
        error("ERROR writing to socket");
    }

    bzero(buffer,256);
    n = read(sockfd,buffer,255);

    if (n < 0)
    {
        error("ERROR reading from socket");
    }

    printf("%s\n", buffer);
    return 0;
}

3 个答案:

答案 0 :(得分:3)

我建议使用BufferedReaderPrintWriter,如下所示

BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); // Bufferreader from socket
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // printwriter from socket

您可以简单地将它们用作

in.readLine(); // read a line

out.println(); // write a line 

如此更新的代码看起来像,

Socket server = serverSocket.accept();

System.out.println("Just connected to " + server.getRemoteSocketAddress());

BufferedReader in = new  BufferedReader( new InputStreamReader(socket.getInputStream()));

System.out.println(in.readline());

PrintWriter out = new PrintWriter(server.getOutputStream());

out.println("Thank you for connecting to ");

此外,如果我更正确,这种方法将满足Java和C的线路终端条件。

答案 1 :(得分:0)

来自readUTF()文档:

  

首先,读取两个字节并用于构造无符号的16位整数,其方式与readUnsignedShort方法完全相同。此整数值称为UTF长度,并指定要读取的其他字节数。

在C客户端中,您没有发送这两个字节。当然,writeUTF()也是如此。

答案 2 :(得分:0)

readUTF()要读取的数据必须由writeUTF(),或可以产生相同protoco的内容发送:l:请参阅Javadoc。由于您的发件人是C,这是不切实际的,因此您应该使用其他读取API,例如readLine(),并在发件人处进行适当调整。