2

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this and I'm still encountering the same problem. Any suggestions as to how I could fix it?
0

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

3 Comments

Okay thanks. What should I do fix this issue? Send 2 bytes in the C client or change the read method in the Java program? ReadUTF seems to be the only way to read a string
@Briscoooe The simplest would be to send the length. It is required anyway, no matter what you do, you must know when the string ends. strlen is enough to know the length, but note that the 2 bytes you must send are big endian.
Would you be able to give me some guidance in relation to how to implement this? Do you have any links for relative tutorials?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.