Reading input from C socket client to Java socket server - java

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

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.

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

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.

Related

C server an Java client socket connection. When reading message on client I see empty spaces before the actual message

I have a Server in C and a client in Java(TCP connection). After I connect them I send the first message from client then a response from the server and everything is ok at this point(client writes in the console the string received) when I send another message to the server and the server gives a response, this response is put at the end of a long String with unkown first characters. For example on the client side I see:
Send a message: type and press Enter key
HELLO
Server: HI
HELLO AGAIN
Server:
HELLO HELLO
Server:
The output on the server side is ok ( both client's and server's messages are seen)
Here is my server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 10011
int main(){
int socketfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
socklen_t addr_size;
char buffer[1024];
pid_t childpid;
socketfd = socket(AF_INET,SOCK_STREAM,0);
if(socketfd < 0){
printf("\n error in socket creation");
return -1;
}
printf("\n Server socket is created\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(socketfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("Error in binding\n");
return -1;
}
printf("[*]Bind to port %d\n", PORT);
if(listen(socketfd, 10) == 0){
printf("Listening...\n");
}else{
printf("Error in binding\n");
}
newSocket = accept(socketfd, (struct sockaddr*)&newAddr, &addr_size);
if( newSocket < 0){
printf("No socket\n");
exit(1);
}
int size = 1024;
char buff[size];
char sbuff[size];
int n;
int reader;
memset(buff, 0, size);
memset(sbuff, 0, size);
// infinite loop for receiving and sending
for (;;) {
// read the message from client and copy it in buffer
reader = recv(newSocket, buff, 1024 * sizeof(char), 0);
if (reader == -1) {
perror("recv()");
break;
} else if (reader == 0) {
break;
} else {
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
bzero(buff, size);
n = 0;
// copy server message in the buffer
while ((sbuff[n++] = getchar()) != '\n');
// and send that buffer to client
write(newSocket, sbuff, sizeof(sbuff));
bzero(sbuff,size);
}
}
close(newSocket);
return 0;
}
and here is my client:
import java.io.*;
import java.net.*;
public class ClientJava
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 10011);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream), 1024);
System.out.println("Send a message: type and press Enter key");
String receiveMessage, sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
// for(int i=0; i<1024;i++){
// String s=receiveRead.read();
// receiveMessage[i]=s;
// if(s == ">") {
// return i;
// }
// }
// System.out.println(receiveMessage);
receiveMessage = receiveRead;
if((receiveMessage) != "0") //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
//removeNonAscii(receiveMessage);
//replaceUnreadable(receiveMessage);
receiveMessage = receiveMessage.substring(0,0);
}
}
private static String removeNonAscii(String s){
StringBuffer sb = new StringBuffer();
for(int i=0; i<s.length(); ++i){
if(s.charAt(i) < 128){
sb.append(s.charAt(i));
}
}
return sb.toString();
}
private static String replaceUnreadable(String s){
String clean = s.replaceAll("\\P{Print}", "");
return clean;
}
}
After debugging I found out that when receiving the message for the second time recieveMessage is full of empty characters and the actual message goes to the end of the String(so it is not visible in the console). How can I clean the String or put the message at the beginning of it? Thanks.
Solved: I used this method
private static String replaceUnreadable(String s){
String clean = s.replaceAll("\\P{Print}", "");
return clean;
}
and it worked

Socket programming Java as Client C as Server endless read of DATAINPUTSTREAM(JAVA)

i'm trying to write a program which uses sockets to send and receive an image.
The Java source should run on android devices. But the class TCP also works on normal java applications.
To be hornest it is just a feature of my whole program.
First of all i want to share my source codes:
Java :
Async (to use it on newer Versions of android >5.**)
class Async extends AsyncTask<String, TCPClient, String> {
#Override
protected String doInBackground(String... args) {
TCPClient cp = new TCPClient();
try {
if (args[1].equals("remote"))
cp.TCPSend(args[0]);
else {
cp.TCPrecv();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
TCP Client:
class TCPClient
{
public void TCPSend(String sentence) throws IOException
{
String modifiedSentence;
Socket clientSocket = new Socket("192.168.0.14", 1334);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
public Bitmap TCPrecv() throws IOException
{
Socket clientSocket = new Socket("192.168.0.14", 1331);
DataInputStream dis;
dis = new DataInputStream(clientSocket.getInputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String size_pic = inFromServer.readLine();
int bytesize=Integer.parseInt(size_pic);
int bytesRead=0;
byte[] pic = new byte[bytesize];
int read=0;
while(read < bytesize && !(bytesRead ==-1)) {
bytesRead = dis.read(pic, 0, 10239);
read += bytesRead;
}
return BitmapFactory.decodeByteArray(pic, 0, pic.length);
}
}
This programm reads a image as a ByteArray. It works for 36/37 packets. Don't matter which size of packets i use. The last packet get lost.
I write some own codes of C Servers but the best code i found on this forum.
The Code snipe contains client and server functions and it works perfect.
But the connection of the the Java Programm works not for all packets.
C Code :
void error(const char *msg)
{
perror(msg);
exit(1);
}
int send_image(int socket){
FILE *picture;
int size, read_size, stat, packet_index;
char send_buffer[10240], read_buffer[256];
packet_index = 1;
picture = fopen("../MR.PNG", "r");
printf("Getting Picture Size\n");
if(picture == NULL) {
printf("Error Opening Image File"); }
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
printf("Total Picture size: %i\n",size);
//Send Picture Size
printf("Sending Picture Size\n");
char *ptr=(char *) malloc(500);
sprintf(ptr,"%d",size);
strcat(ptr,"\n");
write(socket,ptr,20);
//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
/* do { //Read while we get errors that are due to signals.
stat=read(socket, &read_buffer , 255);
printf("Bytes read: %i\n",stat);
} while (stat < 0);*/
printf("Received data in socket\n");
printf("Socket data: %c\n", read_buffer);
while(!feof(picture)) {
//while(packet_index = 1){
//Read from the file into our send buffer
read_size = fread(send_buffer, 1, sizeof(send_buffer)-1, picture);
//Send data through our socket
do{
stat = write(socket, send_buffer, read_size);
}while (stat < 0);
printf("Packet Number: %i\n",packet_index);
printf("Packet Size Sent: %i\n",read_size);
printf(" \n");
printf(" \n");
packet_index++;
//Zero out our send buffer
bzero(send_buffer, sizeof(send_buffer));
int send_image(int socket){
FILE *picture;
int size, read_size, stat, packet_index;
char send_buffer[10240], read_buffer[256];
packet_index = 1;
picture = fopen("../MR.PNG", "r");
printf("Getting Picture Size\n");
if(picture == NULL) {
printf("Error Opening Image File"); }
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
printf("Total Picture size: %i\n",size);
//Send Picture Size
printf("Sending Picture Size\n");
write(socket, (void *)&size, sizeof(int));
//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
do { //Read while we get errors that are due to signals.
stat=read(socket, &read_buffer , 255);
printf("Bytes read: %i\n",stat);
} while (stat < 0);
printf("Received data in socket\n");
printf("Socket data: %c\n", read_buffer);
while(!feof(picture)) {
//while(packet_index = 1){
//Read from the file into our send buffer
read_size = fread(send_buffer, 1, sizeof(send_buffer)-1, picture);
//strcat(send_buffer,"\n");
//Send data through our socket
do{
stat = write(socket, send_buffer, read_size);
}while (stat < 0);
printf("Packet Number: %i\n",packet_index);
printf("Packet Size Sent: %i\n",read_size);
printf(" \n");
printf(" \n");
packet_index++;
//Zero out our send buffer
bzero(send_buffer, sizeof(send_buffer));
}
}
}
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
char contentbuffer[255];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 1331;
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);
while(1)
{
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
int i=0;
send_image(newsockfd);
}
close(newsockfd);
close(sockfd);
return 0;
}
I dont understand why this code 2 times works without problems. But without any changes the last bytes get lost... :-/
Sorry, my english is very badly. But i realy need help. It is so frustrating to debug an program without the knowlege to understand what the problem is.
Sorry again. I have trouble with the code snipes system. It want work on Class TCP Client.
Thank for your attention.
MFG Neks
Edit: After some comments i'm modified my Java Code. Now the same code works on a real Java Programm with Java EE IDE. This program works fine. But the same code want work on Android. I don't understand why. I can post pics of the debugging sessions.
package com.vib;
import java.io.;
import java.net.;
class NewTcpClient {
#SuppressWarnings("resource")
public void TCPrecv() throws IOException {
Socket clientSocket = new Socket("192.168.0.14", 1331);
DataInputStream dis;
dis = new DataInputStream(clientSocket.getInputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String size_pic = inFromServer.readLine();
int bytesize = Integer.parseInt(size_pic);
int bytesizeread = 10239;
int bytesRead = 0;
byte[] pic = new byte[bytesize];
int read = 0;
int count=0;
while (read < bytesize)
{
bytesRead = dis.read(pic, 0, bytesizeread);
read += bytesRead;
count++;
}
clientSocket.close();
System.out.println(pic);
}
public static void main(String argv[]) throws Exception {
NewTcpClient tcp = new NewTcpClient();
tcp.TCPrecv();
}
}
I don't understand whats going on... i uses this programm on normal IDE now for 3 houres... now it want work... without any changes. How can i debugg something so mystil? ^^
After a break of 2 hours the program works fine. What can be a reason for this bug.

sending a string using java from PC to board having Microcontroller connected through a Lan cable

I have a PC and the board with a microcontroller in it. PC and board are connected through LAN cable.
I have a ip address and port number of both PC and board. I want to send a string from my PC to the board.I know we have to use socket programe for this.
I have made my PC as the client and board as the server.
when i run the client program i am getting error as connection refused.
The port number of both are the same.
(This is all about sending a TCP packets).
When i use the same client program to communicate with other computer which is made as server it works.
I have got the code in c++ but i want the code in java for this.
A code for this would be helpful
Thanks in advance
Following is an example taken from java doc:
Server Program:
/** EchoServer.java - Echoes the input from client, this needs to be
* executed from microcontroller
*/
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try {
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: "+inputLine);
System.out.println("Echoing: "+inputLine);
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
Execute the EchoServer.java in microcontroller like the following:
javac EchoServer.java
java EchoServer 5541
Client Program:
/** EchoClient.java - Sends strings to server
* and displays the echoed string from server
*/
import java.io.*;
import java.net.*;
public class EchoClient {
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]);
try {
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
}
Execute the EchoClient.java in PC like the following:
javac EchoClient.java
java EchoClient 110.21.56.74 5541
Here, 110.21.56.74 should be replaced with the IP address of microcontroller.
Program should be terminated from EchoClient by pressing Ctrl+C
Server Program in C
Its been a long while since i worked on C socket programming. The following program from this link worked as expected.
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , read_size;
struct sockaddr_in server , client;
char client_message[2000];
//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( 8888 );
//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 , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
//Receive a message from client
while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
{
printf("Received : %s\n",client_message);
printf("Echoing : %s\n",client_message);
//Send the message back to client
write(client_sock , client_message , strlen(client_message));
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
return 0;
}
Note this C server program uses 8888 as port number.

Strange behavior in TCP transmission

My server-client application consists of the following modules:
client (written in Java) connects to server and sends a file;
server (written in C) receives the file and sends a char array message.
The problem is that after receiving the file, the server is unable to send the message or the client is unable to receive it.
Here is my code for server application:
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c, bytecount, nr_transf, rest_byte, i, bytesRead;
int recv_size, file_size;
char message[1000];
char buffer[1000];
int buffer_len = 1000;
FILE *f = fopen("out.jpg", "wb");
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
getch();
return 0;
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
//Bind
if(bind(s, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
getch();
return 0;
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
printf("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr*)&client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
getch();
return 0;
}
printf("Connection accepted");
//Receive image
while((bytesRead = recv(new_socket, buffer, buffer_len, 0)) > 0)
{
fwrite(buffer, 1, bytesRead, f);
}
fclose(f);
printf("\nReceive finished!");
//Send messsage
char my_message[100];
strcpy(my_message, "Hello World!");
send(new_socket, my_message, strlen(my_message), 0);
closesocket(s);
WSACleanup();
getch();
return 0;
}
And the code for client application:
public class MyClass
{
public static void main(String[] args)
{
String fileName = "1.jpg", receiveMessage;
File a_file = new File(fileName);
int j;
OutputStream output = null;
InputStream input = null;
ObjectInputStream in = null;
Socket socket = null;
try
{
// Create a socket
socket = new Socket("192.168.0.122", 8888);
FileInputStream fileInputStream = new FileInputStream(fileName);
byte[] buffer = new byte[1000];
int bytesRead = 0;
output = socket.getOutputStream();
input = socket.getInputStream();
while((bytesRead = fileInputStream.read(buffer))>0)
{
output.write(buffer,0,bytesRead);
}
fileInputStream.close();
System.out.println("Send finished!");
input.read(buffer);
System.out.println("Receive finished!");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
output.close();
socket.close();
}
catch(Exception e)
{
}
}
}
}
Any ideas to solve this problem? Thanks in advance!
It's because you have blocking sockets. When a socket is created (by connecting or by accepting) it is in blocking mode. This means that if there is no data to receive it will not return, effectively blocking the caller.
So after you received the last byte in the loop in the server, the recv call will block indefinitely.
On Windows with winsockets, you use the ioctlsocket function to make a socket blocking or non-blocking. The linked reference have an example which shows hot to make a socket blocking or non-blocking.

Reading line by line from a socket

I am sending lines through a socket from a client in C, and reading on a server in Java. The best I can manage is that the client send the multiple lines, and when I close the client the server prints all the data in one line. Or to make it that one send then receives, etc. My desire is that the C application sends "Hi" in a loop, and the Java files catches first hi, prints and then catches second and prints. Right now it prints "HiHiHiHi...", but only when the connection is terminated.
I am using oracle socket example as guideline and using another guide for the C client
So reading the socket in Java is:
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connected with client");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("RECEIVING " + inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
Trying to write to the socket in a while loop the same string in C:
void connection(void) {
int sockfd, portno;
struct sockaddr_in serv_addr;
struct hostent *server;
/* Set time limit. */
timeout.tv_sec = 0;
timeout.tv_usec = 10;
portno = 4444;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("Localhost");
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(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1) {
/* Create a descriptor set containing our two sockets. */
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
bzero(buffer,256);
char *buffer2 = "here";
n = write(sockfd,buffer2,strlen(buffer2));
if (n < 0)
error("ERROR writing to socket");
}
}
Your server is waiting for a \n before it prints anything.
Your client isn't sending any \n chars.
You might try:
char *buffer2 = "here"\n;

Categories