简体   繁体   中英

Reading input from C socket client to Java socket server

I have 2 socket clients and 2 socket servers, one of each in C and Java and all running on my local machine as processes.

They can all talk to each other successfully except the C socket and Java server. They connect successfully but when I type input into the C client, the enter key does not finish the message and send it to the Java server in the same manner it does when communicating with the C server.

Any insight would be greatly appreciated.

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 client:

#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;
}

I would suggest to use BufferedReader and PrintWriter as follow,

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

You can simply use them as ,

in.readLine(); // read a line

out.println(); // write a line 

So updated code would look like,

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

Additionally if i'm correct this approach would fulfill line terminal conditions for both Java and C.

From the readUTF() documentation :

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read.

In your C client, you are not sending these two bytes. Of course, this is also true for writeUTF() .

Data to be read by readUTF() must be sent by writeUTF(), or something that can produce the same protoco:l: see the Javadoc. As your sender is C this is not practical, so you should use a different read API, for example readLine(), with suitable adjustment at the sender.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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