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.
Related
I have a C client which uses UDP to send packets to my PC's IP address. Below is the function used to initialize the socket:
void log_init(const char *ipString) {
log_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (log_socket < 0)
return;
struct sockaddr_in connect_addr;
memset(&connect_addr, 0, sizeof(connect_addr));
connect_addr.sin_family = AF_INET;
connect_addr.sin_port = 4405;
inet_aton(ipString, &connect_addr.sin_addr);
if (connect(log_socket, (struct sockaddr *) &connect_addr, sizeof(connect_addr)) < 0) {
socketclose(log_socket);
log_socket = -1;
}
}
Here is the sending code:
void log_print(const char *str) {
// socket is always 0 initially as it is in the BSS
if (log_socket < 0) {
return;
}
int len = strlen(str);
int ret;
while (len > 0) {
int block = len < 1400 ? len : 1400; // take max 1400 bytes per UDP packet
ret = send(log_socket, str, block, 0);
if (ret < 0)
break;
len -= ret;
str += ret;
}
}
In Java, I want to receive those messages but they never arrive, it's always stuck on receive():
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServer
{
public static void main(String[] arguments) throws Exception
{
System.out.println("Binding...");
DatagramSocket serverSocket = new DatagramSocket(4405);
System.out.println("Binded!");
byte[] receiveData = new byte[1400];
while (true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("Receiving...");
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println("Received: " + sentence);
}
}
}
Interestingly, a C server on the same machine as the Java server works just fine and indeed receives the messages. The socket initialization and receive functions are below:
int NetInit()
{
if(sock_id >= 0)
return sock_id;
#ifdef WIN32
WSADATA wsaData;
// Initialize Winsock
if (WSAStartup(MAKEWORD(2,2), &wsaData) == SOCKET_ERROR)
return -1;
#endif
//Get a socket
if((sock_id = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1)
return -1;
#ifdef WIN32
u_long mode = 1;
ioctlsocket(sock_id, FIONBIO, &mode);
#else
int flags = fcntl(sock_id, F_GETFL, 0);
fcntl(sock_id, F_SETFL, flags | O_NONBLOCK);
#endif
return sock_id;
}
int NetRead(void *buffer, unsigned int buf_len)
{
if(sock_id < 0)
return sock_id;
fd_set fdsRead;
FD_ZERO(&fdsRead);
FD_SET(sock_id, &fdsRead);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 10000;
if(select(sock_id + 1, &fdsRead, NULL, NULL, &tv) != 1) {
return 0;
}
int len = sizeof(servaddr);
return recvfrom(sock_id,buffer, buf_len, 0,(struct sockaddr *)&servaddr, &len);
}
How do I get receiving messages to work with Java?
I'm trying to modify a client-server program so that I can connect to the server(which I run in VirtualBox on Linux) which is written in C, from a client which I want to run in Windows, and is written in Java.
I have a few problems though. Here is my server.c file which I run on Linux:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
void deservire_client(int c) {
// serving the client
int nr, i=2, nrDiv=0, sirDiv[10]={0,0,0,0,0,0,0,0,0,0};
recv(c, &nr, sizeof(nr), MSG_WAITALL);
while ( i <= nr/2){
if ( nr%i == 0){
sirDiv[nrDiv]=i;
nrDiv+=1;
}
i+=1;
}
send(c, &sirDiv, sizeof(sirDiv), 0);
close(c);
// ending of serving the client;
}
int main() {
int s;
struct sockaddr_in server, client;
int c, l;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
printf("Creating server socket error!\n");
return 1;
}
memset(&server, 0, sizeof(server));
server.sin_port = htons(1234);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) {
printf("Binding Error!\n");
return 1;
}
listen(s, 5);
l = sizeof(client);
memset(&client, 0, sizeof(client));
while (1) {
c = accept(s, (struct sockaddr *) &client, &l);
printf("S-a conectat un client.\n");
if (fork() == 0) { // fiu
deservire_client(c);
return 0;
}
}
}
As you can see, the server will return an array of integers, which will be the divisors of the number I send in from the client file.
I have written a client file, also in C, just to see if it works. I run them both under Linux though. Here's the file:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
int main() {
int c;
struct sockaddr_in server;
char send_data[1024];
c = socket(AF_INET, SOCK_STREAM, 0);
if (c < 0) {
printf("Creating client socket error!\n");
return 1;
}
memset(&server, 0, sizeof(server));
server.sin_port = htons(1234);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(c, (struct sockaddr *) &server, sizeof(server)) < 0) {
printf("Connecting to server error!\n");
return 1;
}
while(1){
int nr, sirDiv[10]={0,0,0,0,0,0,0,0,0,0}, i=0;
printf("\nInput number: "); scanf("%d",&nr);
send(c ,&nr, sizeof(nr), 0);
recv(c, &sirDiv, sizeof(sirDiv), 0);
printf("\nThe divisors are:\n");
while( i <= 10 ){
if ( sirDiv[i] <= nr/2 && sirDiv[i] != 0)
printf("%d ",sirDiv[i]);
i+=1;
}
printf("\n");
//Ask client if he wants to close
printf("\nq or Q to exit: ");
scanf("%s",send_data);
if (strcmp(send_data , "q") == 0 || strcmp(send_data , "Q") == 0) {
close(c);
break;
}
}
return 0;
}
So this works fine under Linux, and I can connect multiple clients to the server. Now I want to create a client and write it in Java. Here's an example that has been given to me and that I'm trying to modify:
import java.net.*;
import java.io.*;
public class Client2 {
private static final String SERVER_ADDRESS = "127.0.0.1";
private static final int SERVER_PORT = 1234;
private static final int UNSIGNED_SHORT_MAX_VALUE = 65535;
private static final int UNSIGNED_SHORT_MIN_VALUE = 0;
public static void main(String args[]) {
Socket socket = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
int a = readUnsignedShort("a = ", reader);
int b = readUnsignedShort("b = ", reader);
writeIntegersToSocket(a, b, socket);
readIntegersSumFromSocket(socket);
} catch (IOException e) {
System.err.println("Cautgh exception " + e.getMessage());
} finally {
closeStreams(socket,reader);
}
}
private static void readIntegersSumFromSocket(Socket c) throws IOException {
DataInputStream socketIn = new DataInputStream(c.getInputStream());
int s = socketIn.readUnsignedShort();
System.out.println("s = " + s);
}
private static void writeIntegersToSocket(int a, int b, Socket c) throws IOException {
DataOutputStream socketOut = new DataOutputStream(c.getOutputStream());
socketOut.writeShort(a);
socketOut.writeShort(b);
socketOut.flush();
}
private static int readUnsignedShort(String message, BufferedReader reader) throws IOException {
int unsignedShortNumber = 0;
System.out.print(message);
try {
unsignedShortNumber = Integer.parseInt(reader.readLine());
if (unsignedShortNumber < UNSIGNED_SHORT_MIN_VALUE || unsignedShortNumber > UNSIGNED_SHORT_MAX_VALUE) {
throw new IllegalArgumentException("The given number must be unsigned short [0..65535]!");
}
} catch (NumberFormatException e) {
System.err.println("The given input is not an integer!");
}
return unsignedShortNumber;
}
private static void closeStreams(Socket socket, BufferedReader reader) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
System.err.println("Could not close socket!");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Could not close reader!");
}
}
}
}
This example was made for a client-server program which lets the user input two numbers, and the server will return the sum. I have a few problems when I'm trying to modify it though.
public static void main(String args[]) {
Socket socket = null;
int i = 0;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
int nr = readUnsignedShort("nr = ", reader);
while(int i <=10)
int sirDiv[i] = readUnsignedShort("b = ", reader);//Here I have an error, type mismatch, how do I fix this?
writeIntegersToSocket(nr, sirDiv, socket);//Again, how do I write this instead?
readIntegersSumFromSocket(socket);
private static void writeIntegersToSocket(int a, int b, Socket c) throws IOException {
DataOutputStream socketOut = new DataOutputStream(c.getOutputStream());
socketOut.writeShort(nr);
socketOut.writeShort(nrDiv); //will probably have an error here as well
socketOut.flush();
}
Apart from these type mismatches, I still don't know how to connect to the server which I run on linux as in, what do I have to change, the SERVER_ADDRESS or something? Pinging localhost in Linux gives me 127.0.0.1 and pinging 'ping -4 localhost' in Windows gives me the same thing. Could anyone give me a few pointers with this? I've been trying all day.
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.
This question already exists:
client not reading the first message from the server [closed]
Closed 9 years ago.
First, here is my server. Please look at this part
if(clients.size() == 2){
sendStartSignal();
break;
}
In the above part, i send a start signal "start" string when at least two clients connect to the server.
Server code begins here....
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <pthread.h>
#include <vector>
#include <sys/fcntl.h>
using namespace std;
void * handle_client(void * ptr);
void sendStartSignal();
struct thdata{
int client_no;
};
vector<pthread_t *> clients;
vector<int> client_nos;
int main(int argc, char **argv)
{
struct sockaddr_in server_addr,client_addr;
socklen_t clientlen = sizeof(client_addr);
int option, port, reuse;
int server, client;
int nread;
// setup default arguments
port = 3000;
// process command line options using getopt()
// see "man 3 getopt"
while ((option = getopt(argc,argv,"p:")) != -1) {
switch (option) {
case 'p':
port = atoi(optarg);
break;
default:
cout << "server [-p port]" << endl;
exit(EXIT_FAILURE);
}
}
// setup socket address structure
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
// create socket
server = socket(PF_INET,SOCK_STREAM,0);
if (!server) {
perror("socket");
exit(-1);
}
// set socket to immediately reuse port when the application closes
reuse = 1;
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
perror("setsockopt");
exit(-1);
}
// call bind to associate the socket with our local address and
// port
if (bind(server,(const struct sockaddr *)&server_addr,sizeof(server_addr)) < 0) {
perror("bind");
exit(-1);
}
// convert the socket to listen for incoming connections
if (listen(server,SOMAXCONN) < 0) {
perror("listen");
exit(-1);
}
// accept clients
while ((client = accept(server,(struct sockaddr *)&client_addr,&clientlen)) > 0) {
//make the clients non blocking
fcntl(client, F_SETFL, O_NONBLOCK);
pthread_t* th = new pthread_t;
thdata* data = new thdata;
data->client_no = client;
clients.push_back(th);
client_nos.push_back(client);
pthread_create(th, NULL, &handle_client, (void *) data);
if(clients.size() == 2){
sendStartSignal();
break;
}
}
for(int i=0;i<clients.size();i++){
pthread_join(*clients[i], NULL);
}
}
void sendStartSignal(){
char *buf;
int buflen;
int nread;
// allocate buffer
buflen = 1024;
buf = new char[buflen+1];
buf[0] = 's';
buf[1] = 't';
buf[2] = 'a';
buf[3] = 'r';
buf[4] = 't';
buf[5] = 0;
for(int i = 0;i<clients.size();i++) {
send(client_nos[i], buf, 6, 0);
}
}
void * handle_client(void * ptr){
thdata * data = (thdata*) ptr;
char *buf;
int buflen;
int nread;
// allocate buffer
buflen = 1024;
buf = new char[buflen+1];
int client_no = data->client_no;
// loop to handle all requests
while (1) {
// read a request
memset(buf,0,buflen);
nread = recv(client_no,buf,buflen,0);
if(nread >= 0){
if(nread == 0) {
int index_to_delete = -1;
for(int i=0;i<client_nos.size();i++){
if(client_nos[i] == client_no){
index_to_delete = 0;
break;
}
}
clients.erase(clients.begin() + index_to_delete);
client_nos.erase(client_nos.begin() + index_to_delete);
break;
}
for(int i = 0;i<clients.size();i++) {
if (client_nos[i] != client_no){
send(client_nos[i], buf, nread, 0);
}
}
}
}
}
Now, here is my client in java
Please look at this part...
public static void handle_read(){
while(true){
try{
String line = r.readLine();
System.out.println(line);
}
catch(Exception e){
System.err.println(e);
}
}
}
In the above part, it is a thread that just reads incoming message from the server. Now, my question is, as you can see in server code that as soon as two connections are made, "start" signal is sent to the clients....now, the client doesnt print start as soon as two clients connect to the server...it only prints "start" after i send some message to the server. Why is this so?
Client starts here ....
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
public static BufferedReader r;
public static PrintWriter w;
public static void main(String[] args){
try
{
Socket s = new Socket("localhost", 3000);
r = new BufferedReader(new InputStreamReader(s.getInputStream()));
w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
Thread t1 = new Thread(){
public void run(){
handle_read();
}
};
Thread t2 = new Thread(){
public void run(){
handle_write();
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Exiting .... ");
}
catch (Exception err)
{
System.err.println(err);
}
}
public static void handle_read(){
while(true){
try{
String line = r.readLine();
System.out.println(line);
}
catch(Exception e){
System.err.println(e);
}
}
}
public static void handle_write(){
while(true){
try{
Scanner scan = new Scanner(System.in);
String s = scan.next();
w.println(s);
}
catch(Exception e){
System.err.println(e);
}
}
}
}
Thank you!
You are sending this message:
buf[0] = 's';
buf[1] = 't';
buf[2] = 'a';
buf[3] = 'r';
buf[4] = 't';
buf[5] = 0;
Then you are reading it with this code
String line = r.readLine();
This seems like a mismatch. You are not sending a line, but you are trying to read a line.
End the message you send with a newline character, '\n'
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.