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.
Related
I am trying to send a text file from a C server to a Java client. I ran my code and noticed that I'm missing the first (8 characters long) word from my original file but I don't know how to fix that.
Server in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#define PORT htons(12221)
void ServeConnection(int sock)
{
char path[512];
long dl_of_the_file, sent, sent_in_total, read;
struct stat fileinfo;
unsigned char buffer[1024];
FILE* file;
printf("Give the path to the file: \n");
memset(path, 0, 512);
scanf("%s",path);
if (stat(path, &fileinfo) < 0)
{
printf("Child: I can't obtain information about a file\n");
return;
}
if (fileinfo.st_size == 0)
{
printf("Child: filesize 0\n");
return;
}
printf("Child: filesize : %d\n", fileinfo.st_size);
dl_of_the_file = fileinfo.st_size;
sent_in_total = 0;
file = fopen(path, "rb");
if (file == NULL)
{
printf("Child: error at opening a file\n");
return;
}
while (sent_in_total < dl_of_the_file)
{
read = fread(buffer, 1, 1024, file);
sent = send(sock, buffer, read, 0);
if (read != sent)
break;
sent_in_total += sent;
printf("Child: total sent %ld\n", sent_in_total);
}
if (sent_in_total == dl_of_the_file)
{
printf("Child: file sent ok\n");
}
else
{
printf("Child: error at sending a file\n");
}
fclose(file);
return;
}
int main()
{
struct sockaddr_in adr;
socklen_t dladr = sizeof(struct sockaddr_in);
int sock_listen, sock_client;
sock_listen = socket(PF_INET, SOCK_STREAM, 0);
adr.sin_family = AF_INET;
adr.sin_port = PORT;
adr.sin_addr.s_addr = INADDR_ANY;
memset(adr.sin_zero, 0, sizeof(adr.sin_zero));
if (bind(sock_listen, (struct sockaddr*) &adr, dladr) < 0)
{
printf("Parent: bind failed\n");
return 1;
}
listen(sock_listen, 10);
printf("Server running...\n");
while(1)
{
dladr = sizeof(struct sockaddr_in);
sock_client = accept(sock_listen, (struct sockaddr*) &adr, &dladr);
if (sock_client < 0)
{
printf("Parent: accept error\n");
continue;
}
printf("Parent: connection from %s:%u\n",
inet_ntoa(adr.sin_addr),
ntohs(adr.sin_port));
printf("Parent: I'm creating child process\n");
if (fork() == 0)
{
//child
printf("Child: start serving)\n");
ServeConnection(sock_client);
printf("Child: closing socket\n");
close(sock_client);
printf("Child: end of the process\n");
exit(0);
}
else
{
//parent
printf("Parent: return to listening)\n");
continue;
}
}
return 0;
}
and client in java:
package com.company;
import java.net.*;
import java.io.*;
public class Client2 {
public static void main (String [] args ) throws IOException {
Socket socket = new Socket("150.254.79.243", 12221);
System.out.println("Connected");
int bytesRead;
int filesize = 999999999;
byte [] byteArray = new byte [filesize];
InputStream is = socket.getInputStream();
DataInputStream clientData = new DataInputStream(is);
long size = clientData.readLong();
FileOutputStream fos = new FileOutputStream("/Users/adh/Desktop/test/test2.txt");
while ( (bytesRead = clientData.read(byteArray, 0, (int) Math.min(byteArray.length, size))) > -1) {
fos.write(byteArray, 0, bytesRead);
size -= bytesRead;
}
fos.close();
is.close();
socket.close();
}
}
The file I was trying to send: "Hello, how are you?"
What I got: "ow are you?"
How do i resolve this issue?
I think the problem is with the line
long size = clientData.readLong();
As per this, it will read the first 8 bytes, resolved to a long value. It looks like you were trying to use that to find the length of the input stream, but it doesn't work like that and I don't think there's a way to get length of an input stream. Usually, you should send that information first in such a code.
Basically, removing that line and setting size to a big value (for now) should resolve your issue, but you should practice sending the length first in such cases later on.
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 am creating a simple game which consists of Java client and C server. When client sends first request to server, it is ok. The server sends response and client reads it. But when client send second request, the server sends response like always but client reads nothing. When I delete \n from response, clinet is stuck on readLine() which is ok, but when I place \n back, readLine() reads nothing. I am pretty desperate and I tryied variety of actions and changed the message from server like 1000 times but nothing works.
Here is connection method:
public int connect() {
try {
if (port != 0 && !host.equals(null)) {
socket = new Socket(host, port);
socket.setSoTimeout(5000);
socket.setKeepAlive(true);
} else {
socket = new Socket("localhost", 50001);
}
out = new OutputStreamWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException ex1) {
System.out.println("Unknown host: " + host);
return 1;
} catch (IOException ex2) {
System.out.println("No I/O: " + ex2.getMessage());
return 2;
}
return 0;
}
Here are methods for comunication:
public String listRooms() throws DisconnectedException, IOException {
this.send(LIST_ROOMS);
String data = this.receive();
System.out.println("Action: " + LIST_ROOMS + " Result: " + data);
return data;
}
public int createRoom(String playerName) throws IOException, DisconnectedException {
this.send(playerName, CREATE_ROOM);
int result = this.receiveInt();
System.out.println("Action: " + CREATE_ROOM + " Result: " + result);
return result;
}
public void joinRoom(String playerName, int number) throws IOException, DisconnectedException {
String message = number + "\0" + playerName;
this.send(message, JOIN_ROOM);
try {
System.out.println("Action: " + JOIN_ROOM + " Result: " + this.receive());
} catch (SocketTimeoutException e) {
throw new DisconnectedException("Connection with server lost...");
}
}
private void send(String message, int actionNumber) throws IOException {
out.write((char) actionNumber);
out.write(message);
out.flush();
}
private void send(int actionNumber) throws IOException {
out.write((char) actionNumber);
out.flush();
}
private int receiveInt() throws IOException {
int response = in.read();
System.out.println(response);
return 0;
}
private String receive() throws IOException {
String answer = in.readLine();
System.out.println("ANSWER: " + answer);
if (answer == null) {
System.out.println("You recieved nothing Jon Snow...");
} else if ("0".equals(answer)) {
System.out.println("Error recieveing answer from server");
return "0";
}
return answer;
}
and here is server:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "room.h"
void error_message(const char *msg);
typedef struct thread_args
{
int client_sock;
char ip_address[16];
} thread_args;
void *thread_service(void *args)
{
int client_sock;
char buffer[256] = "";
char cbuf;
int n;
char address[16] = "";
int result = 0;
room *room = NULL;
client_sock = ((thread_args *) args)->client_sock;
strcpy(address, ((thread_args *) args)->ip_address);
pthread_detach(pthread_self());
while(1)
{
if ((recv(client_sock, &cbuf, 1, 0)) == -1)
{
printf("Receive message from %s failure\n", address);
break;
}
switch (cbuf) {
case 0:
result = create_room(&room, client_sock);
if(!result)
{
/* TODO */
}
memset(buffer, 0, 256);
sprintf(buffer, "%d\n", result);
n = send(client_sock, buffer, 256, 0);
if (n <= 0) {
perror("ERROR writing to socket\n");
close(client_sock);
break;
}
printf("sent\n");
break;
case 1:
result = join_room(&room, client_sock);
if(!result)
{
/* TODO */
}
printf("Join to room for %s\n", address);
sprintf(buffer, "%d\n", result);
n = send(client_sock, buffer, 256, 0);
if (n <= 0) {
perror("ERROR writing to socket\n");
break;
}
break;
case 2:
printf("List rooms\n");
memset(buffer, 0, 256);
result = list_rooms(buffer);
if(!result) {
/* TODO */
}
printf("Sending message: %s", buffer);
n = send(client_sock, buffer, 256, 0);
if (n <= 0) {
perror("ERROR writing to socket\n");
close(client_sock);
break;
}
printf("Sent\n");
break;
case 5:
exit(0);
break;
}
}
close(client_sock);
free(args);
return 0;
}
int main(int argc, char *argv[])
{
int sock_fd = 0, new_sock_fd = 0, port = 0, clilen = 0;
struct sockaddr_in serv_addr, cli_addr;
int *th_socket;
pthread_t thread_id;
thread_args *args = (thread_args *)malloc(sizeof(thread_args));
char address[16];
int yes = 1;
if(argc < 2)
{
fprintf(stderr, "Error missing port");
return 0;
}
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if(sock_fd < 0)
fprintf(stderr, "Error opening socket");
memset(&serv_addr, 0, sizeof(serv_addr));
port = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == 0)
{
printf("Socket options was set.\n"); //TODO
}
else
{
printf("Set socket options failure.\n"); //TODO
}
if(bind(sock_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error_message("Error in connection");
listen(sock_fd, 5);
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("Mutex init failed.\n");
return 1;
}
while(1)
{
printf("Waiting for new connection\n");
clilen = sizeof(cli_addr);
new_sock_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, &clilen);
if (new_sock_fd < 0) {
printf("Error accepting new connection!\n");
continue;
}
strcpy(args->ip_address, inet_ntoa(cli_addr.sin_addr));
args->client_sock = new_sock_fd;
if (new_sock_fd > 0 ) {
th_socket=malloc(sizeof(int));
*th_socket=new_sock_fd;
printf("Creating new thread for %s\n", args->ip_address);
pthread_create(&thread_id, NULL, (void *)&thread_service, (void *)args);
} else {
printf("Error creating thread for new connection.\n");
return -1;
}
}
return 0;
}
So if you want to send C servera message, it will look like this:
String message = "Hello world!";
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
out.write(message + "\n");
out.flush();
UPDATE: A have figured that out, it was pretty nasty fault, maybe it would help others.. In message from JAVA client to server must be (in my case) manually appended "\n" character, otherwise it sends some characters that will confuse the server. so my code looks like this out.write(message + "\n"); and then just call flush() and it will be ok.
You have to add the enline character, but if you had use the printWriter instead then you could use the println method...
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("Bla bla");
So the answer is simple. If you are using OutputStreamWritter you have to add newline character to your message.
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 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.