TCP client in C and server in Java - java

I would like to communicate with 2 applications : a client in C which send a message to the server in TCP and the server in Java which receive it and send an acknowledgement.
Here is the client (the code is a thread) :
static void *tcp_client(void *p_data)
{
if (p_data != NULL)
{
char const *message = p_data;
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
server = gethostbyname(ALARM_PC_IP);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(TCP_PORT);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
error("ERROR connecting");
}
n = write(sockfd,message,strlen(message));
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("Message from the server : %s\n",buffer);
close(sockfd);
}
return 0;
}
And the java server :
try {
int port = 9015;
ServerSocket server=new ServerSocket(port);
System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":"+port);
System.out.println("Run the Client");
while (true) {
Socket socket=server.accept();
BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
PrintStream out=new PrintStream(socket.getOutputStream());
out.print("Welcome by server\n");
out.flush();
out.close();
in.close();
System.out.println("finished");
}
} catch(Exception err) {
System.err.println("* err"+err);
}
With n = read(sockfd,buffer,255); the client is waiting a response and for the server, the message is never ended so it doesn't send a response with PrintStream.
If I remove these lines :
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0) {
error("ERROR reading from socket");
}
printf("Message from the server : %s\n",buffer);
The server knows that the message is finished but the client can't receive the response.
How solve that ?
Thank you

in.readLine() waits for a NL,CR or CR+NL in the stream. Make sure you are sending that in your client message.

Related

ERROR: Connection refused when connecting to socket server

I have the following C_Client code running well when using 3 terminals,
2 servers and 1 client.
However, when I deployed the same set of codes to 3 different machines,
it doesn't perform as expected.
There are few scenarios,
I am using 8888 port for server1 and 5678 port for server2. The input argument is for client to input.
Connect client and servers on the same machines - work as expected
with argu input: 127.0.0.1 127.0.0.1 8888 5678
Connect client and server2 on the same machines, server1 on the other machines, it also works, with arguments input: 192.168.28.116 127.0.0.1 8888 5678
The problematic scenario, connect client and server2 on different machines, no matter what I have done (such as turn off all firewalls, checking the port if listening or not), the error msg is shown: ERROR connecting tpserver:connection refused.
The argu input:
192.168.28.116 192.168.28.117 8888 5678 or
127.0.0.7 192.168.28.117 8888 5678
From 2, it is sure that the connection on same machine or different machine on server1 doesn't matter, but when connecting server2 on different machine, it weirdly shows error when connecting to server1 socket? Why?
Client.c
//Variable declaration
int sockfd, sockfd2, portno, portno2, n, a, pid, startonce;
struct sockaddr_in serv_addr, serv_addr2;
struct hostent *server, *server2;
//Opening socket
portno = atoi(argv[3]);
portno2 = atoi(argv[4]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
sockfd2 = socket(AF_INET, SOCK_STREAM, 0);
if ((sockfd < 0) || (sockfd2 < 0)) {
error("ERROR opening socket");
}
server = gethostbyname(argv[1]);
server2 = gethostbyname(argv[2]);
if (server == NULL){
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
//Serv_addr for tpServer
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("ERROR connecting tpserver");
}
//Serv_addr for resultServer
bzero((char *) &serv_addr2, sizeof(serv_addr2));
serv_addr2 = serv_addr;
serv_addr2.sin_port = htons(portno2);
if (connect(sockfd2, (struct sockaddr *) &serv_addr2, sizeof(serv_addr2)) < 0) {
error("ERROR connecting resultserver");
}
Server1.c
//Declare variables here
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2) {
fprintf(stderr, "ERROR, no port provided\n");
exit(1);
}
//Opening socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
//Filling info for serv_addr
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("ERROR on binding");
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
//Fork when there a successful connection
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
error("ERROR on accept");
}
pid = fork();
if (pid < 0) {
error("ERROR on fork");
}
if (pid == 0) {
close(sockfd);
dostuff(newsockfd);
exit(0);
}
else close(newsockfd);
}
close(sockfd);
return 0;
}
Server2.java
public void startServer(final int portno) {
try {
ServerSocket serverSocket = new ServerSocket(portno);
System.out.println("Waiting for clients to connect...");
while (true) {
try {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
catch (IOException e) {
System.err.println("Unable to process client request");
e.printStackTrace();
}
}
}
catch (IOException e) {
System.err.println("Unable to process client request");
e.printStackTrace();
}
}
Update 2016/5/17 11:44
I changed the code from :
//Serv_addr for resultServer
bzero((char *) &serv_addr2, sizeof(serv_addr2));
serv_addr2 = serv_addr; //Copied tpServer socket to resultServer info for local testing
serv_addr2.sin_port = htons(portno2);
if (connect(sockfd2, (struct sockaddr *) &serv_addr2, sizeof(serv_addr2)) < 0) {
error("ERROR connecting resultserver");
}
to
//Serv_addr for resultServer
bzero((char *) &serv_addr2, sizeof(serv_addr2));
serv_addr2.sin_family = AF_INET;
bcopy((char *)server2->h_addr, (char *)&serv_addr2.sin_addr.s_addr, server2->h_length);
serv_addr2.sin_port = htons(portno2);
if (connect(sockfd2, (struct sockaddr *) &serv_addr2, sizeof(serv_addr2)) < 0) {
error("ERROR connecting resultserver");
}
But I still getting the same error message:
./tp_client 192.168.28.152 192.168.28.130 8888 5678
ERROR connecting tpserver: Connection refused
Update 2016/5/17 11:49
I tried using another linux machine and it connected to both server successfully, but when I set up the server2 on windows, it still shows connection refused.
So now, it works on 3 different linux but not linux to windows? I tested my server on windows with browser and it works like charm. How do I connect my linux client to windows server?
Update 2016/5/18 10:52
New discovery, when client connect to 2 servers, the 2 ips must be the same rather than on 2 different server machines, no matter windows or not.If they are the same, the connection is established,if not, connection refused. i included the perror() function but still getting the same msg: connection refused, is there any problem when i declare socket in client.c?
So at the end, it turns out that the method:gethostbyname is deprecated and failed to response to the request. After updated to the method:getaddrinfo, the problem solved.
The code now:
client.c
int sockfd, sockfd2;
struct addrinfo hints, *servinfo, *p;
struct addrinfo hints2, *servinfo2, *p2;
int rv, rv2;
//Opening socket
memset(&hints, 0, sizeof(hints));
memset(&hints2, 0, sizeof(hints2));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints2.ai_family = AF_UNSPEC;
hints2.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], argv[3], &hints, &servinfo)) != 0) {
fprintf(stderr, "tpgetaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
if ((rv2 = getaddrinfo(argv[2], argv[4], &hints2, &servinfo2)) != 0) {
fprintf(stderr, "rsgetaddrinfo: %s\n", gai_strerror(rv2));
exit(1);
}
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("tpsocket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
perror("tpconnect");
close(sockfd);
continue;
}
break;
}
for (p2 = servinfo2; p2 != NULL; p2 = p2->ai_next) {
if ((sockfd2 = socket(p2->ai_family, p2->ai_socktype, p2->ai_protocol)) == -1) {
perror("rssocket");
continue;
}
if (connect(sockfd2, p2->ai_addr, p2->ai_addrlen) == -1) {
perror("rsconnect");
close(sockfd2);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "failed to connect tpserver\n");
exit(2);
}
if (p2 == NULL) {
fprintf(stderr, "failed to connect rsserver\n");
exit(2);
}
freeaddrinfo(servinfo);
freeaddrinfo(servinfo2);

Why my android client cannot receive string message from winsock c++ server?

I am trying to build an android app that communicates with a c++ server running on windows using TCP sockets. I successfully sent a string from the app to the server but I cannot do the other way around. Please help me because I have been trying with this issue for a while now.
Android Client:
String mystr="Hello World...";
char[] buffin=new char[128];
String input =null;
Integer count = 0;
class TextRcv extends AsyncTask<Void, Void, Integer>
{
#Override
protected Integer doInBackground(Void... params) {
//Sending a string (WORKING)
Socket clientSocket = null;
try {
clientSocket= new Socket("192.168.1.5",8889);
DataOutputStream oos= new DataOutputStream(clientSocket.getOutputStream());
oos.writeBytes(mystr);
//oos.writeBytes(String.valueOf(mystr.length()));//write the length of the string first
//byte[] bufferout=mystr.getBytes();
//oos.write(bufferout, 0, bufferout.length);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
//Recieving a String (Not working)
try {
BufferedReader in = null;
if (clientSocket != null)
{
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
else
{
Log.e("samer ","CLIENTSOCKET NULL");
}
if (in != null)
{
count=in.read(buffin);
}
else
{
Log.e("samer ","BUFFERREADER NULL");
}
if(count>0)
{
input=new String(buffin,0,count);
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
Log.i("samer count: ",String.valueOf(count));//RETURNS 0 !!
Log.i("buff samer: ", String.valueOf(buffin));//Returns garbage
e.printStackTrace();
}
return count;
}
#Override
protected void onPostExecute(Integer count) {
super.onPostExecute(count);
Toast toast=Toast.makeText(getApplicationContext(),String.valueOf(count),Toast.LENGTH_LONG);
toast.show();
}
}
The 'count' always returns 0 despite the fact that on the windows c++ server side it says that it has successfully sent the 25 bytes.
C++ Winsock Server:
int main(int argc, const char *argv[])
{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int valread;
int iSendResult;
char * recvbuf;
char *recvstr;
int recvbuflen = DEFAULT_BUFLEN;
recvbuf = (char*)malloc((recvbuflen + 1) * sizeof(char));
recvstr = (char*)malloc((recvbuflen + 1) * sizeof(char));
char* AndroidID;
char *sendbuf = "Client: sending data test";
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
if (ClientSocket != INVALID_SOCKET)
{
cout << "Start Receving" << endl;
//------Start Receiving
//-----------------------------------
int lengthofrecv=recv(ClientSocket, recvbuf, recvbuflen, 0);
recvbuf[lengthofrecv] = '\0';//append \0 to use with printf()
AndroidID = recvbuf;
printf("AndroidID - %s \n", recvbuf);
cout << " \n Done ";
//---Start Sending to android
//-----------------------------------------
iResult = send(ClientSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR)
{
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %d\n", iResult);
cout << WSAGetLastError() << endl;
}
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
Server console output:
Start Receving
AndroidID - Hello World...
Done Bytes Sent: 25
0
Press any key to continue . . .
The problem is that you are calling oos.close() after sending the initial string to the server.
DataOutputStream extends FilterOutputStream, and the behavior of its close() method is documented:
FilterOutputStream.close()
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.
In this case, the "underlying output stream" is the socket's outputStream, and its close() behavior is also documented:
Socket.getOutputStream()
Closing the returned OutputStream will close the associated socket.
Socket.close()
Closes this socket.
Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.
Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.
Closing this socket will also close the socket's InputStream and OutputStream.
If this socket has an associated channel then the channel is closed as well.
So, your client is closing the socket connection before it can read the server's reply string. You need to remove that call to oos.close() so yo keep the connection open until you are done reading.
On the server side, simply due to timing, your code may be able to call send() and put the reply string into the socket's outbound buffer before the socket detects the disconnect. The buffer is not actually transmitted by send() itself, it is queued to the OS kernel, which will transmit the data in the background. So send() will return success instead of failure if the reply string is buffered before the disconnect is detected.

Data not received in c server while using executor service from a java client

i have a simple c server and java client implementation and i am testing the server for request handling. I am using executor service for simulating simultaneous requests.
Mechanism : The sever just reads a string from client and acknowledges it by sending back a message to the client.
Issue : For some requests the server doesn't get the message which was sent by the client.
C server:
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h> //write
#include <pthread.h> //for threading , link with lpthread
//the thread function
void *connection_handler(void *);
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c;
struct sockaddr_in server , client;
static int client_count = 0;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 5000 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 1000);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
pthread_t thread_id;
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
client_count++;
printf("Connection accepted for client no : %d\n",client_count);
if( pthread_create( &thread_id , NULL , connection_handler , (void*) &client_sock) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
//pthread_join( thread_id , NULL);
puts("Handler assigned");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size, t = 0, operation = -1, buffer_size = 0;
char *message , recv_meta[2000], *data[3];
//Receive a message from client
while(read_size = recv(sock, recv_meta, 2000, 0) > 0 ) {
printf("Meta from client : %s\n",recv_meta);
sprintf(recv_meta, "%s", "OK, Meta Data received!");
send(sock, recv_meta, strlen(recv_meta), 0); //send acknowledgement
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
return 0;
}
Java Client:
import java.net.*;
import java.io.*;
import java.util.Arrays;
import java.util.concurrent.*;
public class client
{
public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 5; i++) {
Runnable worker = new WorkerThread(""+i);
executorService.execute(worker);
}
executorService.shutdown();
}
}
class WorkerThread implements Runnable {
String clientcount = "";
public WorkerThread(String s){
this. clientcount=s;
}
#Override
public void run() {
Socket socket = null;
int PORT = 5000, buffer_size = 0;
String meta = " ";
meta = "newfileidforenc:1:20000";
// Create the socket connection to the EchoServer.
try
{
socket = new Socket("localhost", PORT);
}
catch(UnknownHostException uhe)
{
// Host unreachable
System.out.println("Unknown Host");
}
catch(IOException ioe)
{
// Cannot connect to port on given host
System.out.println("Cant connect to server at port "+PORT+". Make sure it is running.");
return;
}
try
{
PrintWriter pout = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader pin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pout.println(meta);
pout.flush();
System.out.println("\nServer Says : " + pin.readLine() + "for "+ clientcount);
}
catch(Exception ioe)
{
System.out.println("\nException during communication. Server probably closed connection.");
}
finally
{
try
{
// Close the socket before quitting
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Output : It is not the same. All the client gets connected and disconnect successfully. But the server doesn't receive and print the data from all the clients.
You have numerous problems with:
1) Not correctly handling TCP streams and assuming that TCP transfers messages instead of octet, (byte) streams.
2) Not appreciating the C-style null-terminated char arrays that msaquerade as a string type.
3) Passing values by address to thread create calls.
See comments.
I found a solution for the issue.
Actual issue : Executor service is used for load testing i.e., there would be more number of requests sent per second. Under such heavy load the code enters a race condition. The client_sock whose address is passed to the pthread_create() is being overwritten by the next accept() call before it is copied to the sock variable inside the connection_handler(). This leads to a scenario where a single connection would be processed by two or more threads and some other connections are left unhandled.
Solution : Copy the client_sock to a string buffer which should be passed as the argument for pthread_create().
Hope it will be useful.

Socket communication, Java client C server

I am trying to communicate through sockets a Java client and a C server
All seems to work fine if I try the server using nc on the command line to connect or if I use nc as a server and connect with my Java client, but when I try to connect Java Client and C server it doesn't work.
The client starts the connection, and sends the message, message is received by the server but then serverĀ“s response never arrives to client.
Server Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <unistd.h>
int main( int argc, char *argv[] )
{
int sockfd, clisockfd, portno;
char * start = "hello";
char * end = "bye";
socklen_t clilen;
char buffer[256];
char contentBuffer[255];
struct sockaddr_in serv_addr, cli_addr;
int n;
//int optval;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
return(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5000;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
return(1);
}
listen(sockfd,5);
clilen = (socklen_t) sizeof(cli_addr);
clisockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (clisockfd < 0)
{
perror("ERROR on accept");
return(1);
}
while (strcmp(end, contentBuffer) !=0)
{
bzero(buffer,256);
bzero(contentBuffer,255);
/* If connection is established then start communicating */
n = read( clisockfd,buffer,255 );
if (n < 0)
{
perror("ERROR reading from socket");
return(1);
}
strncpy(contentBuffer,buffer,strlen(buffer) - 1);
if (strcmp(start, contentBuffer) ==0)
{
printf("command: %s\n",buffer);
n = write(clisockfd,"Roger that",11);
if (n < 0)
{
perror("ERROR writing to socket");
return(1);
}
}
else
{
printf("Unknown command: %s\n",buffer);
n = write(clisockfd,"ERRCmd",7);
if (n < 0)
{
perror("ERROR writing to socket");
return(1);
}
}
}
close(sockfd);
return 0;
}
Client Code:
import java.io.*;
import java.net.*;
public class Cliente {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
Socket firstSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(firstSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(firstSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
System.out.println("received: " + in.readLine());
}
in.close();
stdIn.close();
firstSocket.close();
}
}
readLine() blocks until the connection had been shutdown() or close()d or it received a new-line \n, which never is sent by the server.

Trouble receiving data to Java socket client from C socket server

I'm having a problem trying to send strings back and forth between a simple Java socket client and a simple C socket server.
It works as follows:
Java client sends msg to C server
out.writeBytes(msg);
C server receives the msg and puts into buf
if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
C server sends the messsage back to the Java client
if ((len = send(new_fd, buf, numbytes, 0)) == -1)
perror("send");
However the Java client cannot receive the msg from the C server, I've tried using DataInputStream, BufferedReader, reading into char[], byte[], converting to string but cannot get the received message. When trying to read into an array on the client side I sometimes get only the first character which leads me to believe it's a blocking problem?
Any help would be appreciated
Code:
C server main loop
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("msg size: '%d' bytes\n",numbytes);
printf("received msg: %s\n",buf);
char* array = (char*)buf;
printf("as char array: %s\n", array);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
int len = 0;
if ((len = send(new_fd, buf, numbytes, 0)) == -1)
perror("send");
printf("sent %d bytes\n", len);
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
Java client
public void send(String text){
Socket sock = null;
DataInputStream in = null;
DataOutputStream out = null;
BufferedReader inReader = null;
try {
sock = new Socket(HOST, PORT);
System.out.println("Connected");
in = new DataInputStream(sock.getInputStream());
out = new DataOutputStream(sock.getOutputStream());
out.writeBytes(text + "\n");
String res = "";
//get msg from c server and store into res
System.out.println("Response: " + res);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
sock.close();
//in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources