1

This is my c code. It is receiving the data send by the client and sending hello to the client.

#include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include<errno.h> #include<arpa/inet.h> #define PORT 6865 #define BUF 1024 int main(int argc, char *argv[]) { struct sockaddr_in host, remote; int host_fd, remote_fd; int size = sizeof(struct sockaddr);; int read_t; char send_t[]="hello"; char data[BUF]; host.sin_family = AF_INET; host.sin_addr.s_addr = htonl(INADDR_ANY); host.sin_port = htons(PORT); memset(&host.sin_zero, 0, sizeof(host.sin_zero)); host_fd = socket(AF_INET, SOCK_STREAM, 0); if(host_fd == -1) { printf("socket error %d\n", host_fd); return 1; } if(bind(host_fd, (struct sockaddr *)&host, size)) { perror("bind error is\n"); printf("errorno is %d\n",errno); return 1; } if(listen(host_fd, 5)) { printf("listen error"); return 1; } printf("Server setup, waiting for connection...\n"); remote_fd = accept(host_fd, (struct sockaddr *)&remote, &size); printf("connection made\n"); read_t = recv(remote_fd,data,sizeof(data),0); data[read_t]='\0'; printf("read = %d, data = %s\n", read_t, data); if(send(remote_fd,send_t,sizeof(send_t),0)==-1) { printf("error in sending back\n"); return 1; } //memset(data[BUF],0,sizeof(data)); //read_t = recv(remote_fd,data,sizeof(data),0); //data[read_t]='\0'; //printf("read = %d, received_data = %s \n", sizeof(data), data); shutdown(remote_fd, SHUT_RDWR); close(remote_fd); return 0; } 

This is the client java code.

package pack.client; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) throws UnknownHostException, IOException { char[] data = new char[10]; OutputStreamWriter outs = null; InputStreamReader ins= null; Socket s = new Socket("10.9.79.80", 6865); outs = new OutputStreamWriter(s.getOutputStream()); outs.append("Socket communication"); ins= new InputStreamReader(s.getInputStream()); int da = ins.read(data, 0, 9); System.out.print(data); outs.close(); ins.close(); s.close(); } } 

When the client is making connection with server, I can see the connection made message on the terminal but the server is not receiving the data.

1 Answer 1

1

You need to flush output stream after writing to server.

 outs.append("Socket communication"); // or try this outs.write("Socket communication"); outs.flush(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.