Problem when sending messages from client socket to server socket - java

I'm new to socket. I want to make a client-server program but I have a problem when it comes to printing messages on the side of the server. That leads me to believe there is a problem in my Client class when it is sending the messages. The first message that is sent from client to server is delivered fine but the rest aren't printed even though the sequence number is printed.
Here are both classes:
Client class:
public class Cliente extends Conexion {
private String mensaje;
private String recibeTeclado;
int numSec = 0;
String tipo = "0";
private int num;
int c;
public Cliente() throws IOException{
super("cliente");
}
public void startClient() {
try {
salidaServidor = new DataOutputStream(cs.getOutputStream());
Scanner lee = new Scanner(System.in);
System.out.println("How many messages do you want to send?");
num = lee.nextInt();
salidaServidor.writeUTF(":" + num + "\n");
for (int i = 1; i <= num; i++) {
numSec++;
System.out.println("Enter the message: ");
recibeTeclado = lee.next();
mensaje = tipo + ":" + Integer.toString(numSec) + ":" + recibeTeclado + "\n";
salidaServidor.writeUTF(mensaje);
salidaServidor.flush();
BufferedReader in = new BufferedReader (new InputStreamReader (cs.getInputStream()));
String mensajeDelServidor = in.readLine();
System.out.println("Status : " + mensajeDelServidor);
}
cs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Server class:
public class Servidor extends Conexion{
String nuevo;
int numSec=0;
String tipo="1";
int num;
String [] n;
public Servidor() throws IOException{super("servidor");}
public void startServer() {
try {
System.out.println("Waiting...");
cs = ss.accept();
BufferedReader numString = new BufferedReader(new InputStreamReader(cs.getInputStream()));
n=numString.readLine().split(":");
num=Integer.parseInt(n[1]);
for(int i=1; i<=num; i++) {
salidaCliente=new DataOutputStream(cs.getOutputStream());
numSec++;
System.out.println(numSec);
nuevo= tipo +":"+ Integer.toString(numSec) +":"+ "Received\n";
salidaCliente.writeUTF(nuevo);
salidaCliente.flush();
BufferedReader entrada = new BufferedReader(new InputStreamReader(cs.getInputStream()));
boolean band=false;
while((mensajeServidor=entrada.readLine())!=null && !band) {
String[] arrSplit = mensajeServidor.split(":");
System.out.println(arrSplit[2]);
band=true;
}
}
System.out.println("Fin de la conexión");
ss.close();
cs.close();
}catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}

[Updated, thanks to #user207421's comment]
2 solutions
Keep using DataOutputStream.writeUTF
Then you have to use DataInputStream.readUTF instead of BufferedReader.readLine.
And if you want to use '\n' as a separator, you will have to detect such characters
Keep using BufferedReader.readLine
Then you have to use an output stream method like Writer.write instead of DataOutputStream.writeUTF.
Use only one BufferedReader instance, on server side at least (numString will keep buffered data that will not be available for the entrada instance).
For UTF-8, use:
BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream(), "UTF-8"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream(), "UTF-8"));

On the client side, you should use a PrintWriter instead of a DataOutputStream to write data to the server:
salidaServidor = new PrintWriter(cs.getOutputStream(), true);
On the server side, 'salidaCliente' should also be a PrintWriter.

Related

how to close a buffered reader when in mid communication

I need a bufferread to work with a client which closes when the word "CLOSE". THE client closes, I just can't get the sever to close once messages have been sent through it.
Heres what code I have:
`
import java.io.*;
import java.net.*;
class TCPClient2 {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser
= new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("143.53.30.136", 49250);//port number and ip address of client
DataOutputStream outToServer
= new DataOutputStream(clientSocket.getOutputStream());
InputStream sin = clientSocket.getInputStream();
// Just converting them to different streams, so that string handling becomes easier.
DataInputStream inFromServer = new DataInputStream(sin);
try {
do {
System.out.print("Enter message : ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
//Question B4
//if statement for closing the socket connection
if (sentence.equals("CLOSE")) {
clientSocket.close();
//closes client socket
System.out.println("Socket Closed");
//prints socket closed to tell user socket has closed
System.exit(0);
}
outToServer.writeBytes(sentence + '\n');
System.out.print("Message sent! please wait for server message: ");
modifiedSentence = inFromServer.readUTF();
System.out.println("FROM SERVER: " + modifiedSentence);
} while (!sentence.equals("CLOSE"));
} catch (IOException e) {
}
clientSocket.close();
}
}`
AND the server:
`
/*
chris and paul
*/
import java.io.*;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPMultiThreadServer {
private static ServerSocket welcomeSocket;
//port number the server is using
private static final int PORT = 49250;
private static int clientNo =1;
public static void main(String argv[]) throws Exception
{
System.out.println("Opening port...\n");
try
{
// ServerSocket listens for new connections on specified port
welcomeSocket = new ServerSocket(PORT);
do
{
Socket client = welcomeSocket.accept();
System.out.println("\nNew client accepted.\n");
//Create a thread to handle communication with
//this client and pass the constructor for this
//thread a reference to the relevant socket...
TCPMultiThreadServer.ClientHandler handler =
new TCPMultiThreadServer().new ClientHandler(client,clientNo);
handler.start(); // Calls run() method in ClientHandler
clientNo++;
} while (true);
} catch (IOException e) {}
}
// Original work not credited
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader inFromClient;
private BufferedReader text_to_Client;
private DataOutputStream outToClient;
private FileWriter Filestream;
private BufferedWriter out;
public int clientNo;
public boolean stopping;
//part A question 4, adding buffer string array to the program
private String[] buffer; //creation of buffer string array.
private int bufferI; // Index of the last thing inserted into the array
public ClientHandler(Socket socket, int clientNos)
{
//Set up reference to associated socket
client = socket;
clientNo= clientNos;
try
{
// Gets access to input/output stream of socket
inFromClient =
new BufferedReader(new InputStreamReader
(client.getInputStream()));
text_to_Client =
new BufferedReader(new InputStreamReader(System.in));
outToClient =
new DataOutputStream(client.getOutputStream());
} catch(IOException e) {}
}
public void run()
{
try
{
stopping = false;
//Question A4 buffer continued
buffer = new String[4];
//generates buffer string array containing 4 strings
bufferI = 0;
// make sure bufferIndex = 0
String clientSentence;
Thread mythread = Thread.currentThread();
do
{
//Accept message from client on socket's input stream
OutputStream sout = client.getOutputStream();
// Just converting them to different streams, so that string
// handling becomes easier.
DataOutputStream text_to_send = new DataOutputStream(sout);
clientSentence = inFromClient.readLine();
System.out.println("Message received from client number " +
clientNo + ": "+ clientSentence);
// String to be scanned to find the pattern.
String line = clientSentence;
String pattern = "[C][L][O][S][E]";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//if (m.find( )) {
// System.out.println("Found value: " + m.find() );
// System.out.println("Found value: " + m.group(1) );
//System.out.println("Found value: " + m.group(2) );
//} else {
// System.out.println("NO MATCH");
//}
//part B question 4 close command
//if statement for closing the socket connection if it is equal to close
if(m.matches())
{ //prints socket closed to tell user socket has closed
System.out.println("Socket connection to client number "
+ clientNo + " closed");
try
{
} catch(Exception e) {}
out.flush();
out.close(); // Close the file handler
client.close(); // Close the connection with the client,
clientNo--; // Decrement the number of clients
}
else
{
//part A question 4, adding buffer string array to the program
// looks to see if the buffer string array is full
//and also looks to see if bufferIndex is in range
if (bufferI > buffer.length-1)
{
// Print BUFFER FULL
System.out.println("BUFFER FULL");
// Clear clientSentence string
clientSentence = " ";
// For loop which travels through the buffer array of string
for (int i=0; i<buffer.length; i++)
{
// Append buffer element to clientSentence string
clientSentence += buffer[i] + " , ";
buffer[i] = null; // makes the buffer null
}
bufferI = 0; // Reset bufferI back to 0 so writing to the buffer can restarted
// prints buffer cleared back to the clients
text_to_send.writeUTF("BUFFER CLEARED :" +
clientSentence);
}
else
{
buffer[bufferI] = clientSentence;
System.out.println("Buffer " + bufferI+ ": " +
buffer[bufferI]);
bufferI++;
System.out.println("Enter Message: ");
// Reads message from server interface
// and sends it to the client
clientSentence = text_to_Client.readLine();
text_to_send.writeUTF(clientSentence);
System.out.println("Your message: " +
clientSentence);
}
}
if (mythread.activeCount() == 2 &&
(clientNo ==0 || clientNo >0) &&
clientSentence.equals("CLOSE"))
{
System.exit(0);
}
} while(!clientSentence.equals("CLOSE"));
client.close();
} catch(IOException e) {}
}
}
}
`

java socket programming blocking on read and write to and from server&client

i have client server socket programming in java .
Server: Multi-threading server to serve the client for math calculations ,eg: sum of all numbers provided from client etc....
client: is to connect to the server and select specif math operations addition,subtraction ...
etc ,and provide the numbers to the server to return the result,and maybe the results is single value or maybe the result from server is array of numbers and depends on the type of the operation...
my Problem is: reading and writing blocking from server to client and vice-versa
eg:
**server->client :*** Welcome to the Calculation Server
server->client: "*** Please type in the num of rows: \n"
client->server: the user insert num of rows and send it to server
server->client: "*** Please type in the num of cols: \n"
client->server: the user insert num of columns and send it to server
server->client:writer.write("Enter the elements of first matrix");
client->server: at the client side it blocks or hang i dont know y???**
the server send
part of server code
import java.net.*;
import java.io.*;
class server_thread extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
int port=10008;
try {
serverSocket = new ServerSocket(port);
System.out.println ("Connection Socket Created on port : "+port);
try {
while (true)
{
System.out.println ("Waiting for Connection");
new server_thread (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private server_thread (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sinput_row, sinput_col,srow_count, scol_count;
int row_count, col_count;
writer.write("*** Welcome to the Calculation Server ( ***\r\n");
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("*** Please type in the num of rows: \n");
writer.flush();
sinput_row = reader.readLine().trim();
int input_row=Integer.parseInt(sinput_row);
System.out.println("num of rows got:"+input_row);
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("*** Please type in the num of cols: \n");
writer.flush();
sinput_col = reader.readLine().trim();
int input_col=Integer.parseInt(sinput_col);
System.out.println("num of Cols got:"+input_col);
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
writer.write("Enter the elements of first matrix");
writer.flush();
int first[][] = new int[input_row][input_col];
int second[][] = new int[input_row][input_col];
int sum[][] = new int[input_row][input_col];
for ( row_count = 0 ; row_count < input_row ; row_count++ )
for ( col_count = 0 ; col_count < input_col ; col_count++ )
{
String s_matrix1_element=reader.readLine().trim();
int matrix1_element=Integer.parseInt(s_matrix1_element);
first[row_count][col_count] = matrix1_element;
}
// the rest of code is ommited for simplicty of analysis
////////////////////////////////////////////////////////////////////////////////////////////////
//int result=num1+num2;
System.out.println("Addition operation done " );
writer.flush();
writer.write("");
//writer.write("\r\n=== Result is : "+result);
writer.flush();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
and here is client code :
import java.io.*;
import java.net.*;
import java.util.*;
public class client_thread {
public static void main(String argv[])
{
try{
Socket socketClient= new Socket("localhost",10008);
System.out.println("Client: "+"Connection Established");
BufferedReader reader =
new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String serverMsg;
String userInput;
writer.flush();
serverMsg = reader.readLine();
System.out.println("from server: " + serverMsg);
while((serverMsg = reader.readLine()) != null )
{
System.out.println("from server inside loop: " + serverMsg);
userInput = stdIn.readLine();
writer.write(userInput+"\r\n");
writer.flush();
}
}catch(Exception e){e.printStackTrace();}
}
}
so the problem
Your server writes:
writer.write("Enter the elements of first matrix");
And the client reads this using
while((serverMsg = reader.readLine()) != null)
So, since the server doesn't send any end of line, the clients waits for it.
Method 1:
Use 1 thread to handle your input stream and another thread to handle your output stream. Then you can do you read and write concurrently.
Method 2:
Use NIO (Non Blocking I/O).

Labview TCP connection with Java

I'm trying to send data from Labview over a TCP socket and receiving the data with Java.
I'm using an example TCP VI from Labview (I cant post pictures).
I realize there's a TCP read, I haven't gotten to that point yet. My problem is dealing with types.
import java.io.*;
import java.net.*;
public class JavaApplication3 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("97.77.53.127");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 6340);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
My first problem I want to deal with, is whenever I receive a input from the Labview VI, in the java program I get:
input: d
echo: ?��/�?�~gʕ ?�$���;P?��G��j�?��"�?�?��;���h?�
input: input: d
echo: ?��/�?�~gʕ ?�$���;P?��G��j�?��"�?�?��;���h?�
input:
I'm assuming my problem is with type casting, but I really don't know enough to fix it.
Any help would be appreciated.
Ok, then try something like:
int temp = 0;
while( (temp = in.read()) != -1){
System.out.print( (char)temp );
}
Just put this somewhere in your code. This simply casts the int returned to a char value, which will print out the letters.
Let me know how it goes.

Java Socket - send many message

I have two simple classes:
Client:
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName(null);
Socket socket = null;
try {
socket = new Socket(addr, 1050);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
in = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter( socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, false);
stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
// read user input
while (true) {
userInput = stdIn.readLine();
System.out.println("Send: " + userInput);
out.println(userInput);
out.flush();
String line = in.readLine();
while(line != null){
System.out.println(line);
line = in.readLine();
}
System.out.println("END");
}
}
catch (UnknownHostException e) {
// ...
} catch (IOException e) {
// ...
}
// close
out.close();
stdIn.close();
socket.close();
}
Server:
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter out = new PrintWriter(bw, /*autoflush*/true);
private void sendMessage(String msg1, String msg2) {
out.println(msg1);
// empy row
out.println("");
out.println(msg2);
}
The user enters a message, and this is sent to the server. Then, the server responds with N messages.
After the first request, the client stops and is never printed the word "END".
How do I send multiple messages at different times, with only one socket connection?
Firstly, you don't need to send an empty row, because you are sending by "line" and recieving by "line".
out.println(msg1);
out.println(msg2);
and
userInput = stdIn.readLine();
Here, userInput will only equal msg1
What I would recommend, would be not to loop on stdIn.readLine() = null, but have the client send, for example, "END_MSG", to notify the server that it will not send anymore messages.
Perhaps something like...
SERVER:
userInput =stdIn.readLine();
if(userInput.Equals("START_MSG");
boolean reading=true;
while(reading)
{
userInput=stdIn.readLine();
if(userInput.Equals("END_MSG")
{
//END LOOP!
reading = false;
}
else
{
//You have received a msg - do what you want here
}
}
EDIT:CLIENT:
private void sendMessage(String msg1, String msg2) {
out.println("START_MSG");
out.println(msg1);
out.println(msg2);
out.println("END_MSG");
}
(It also looks like in your question to have mixed up the client and the server?)

One thread stopping too early regardless of CyclicBarrier

I am aware of the fact that the following code may seem vulgar, but I am new to these things and just tried everything in order to get it to work..
Problem: Even though I am using (possible in a wrong way) a CyclicBarrier, one - and seems to always be the same - thread stops too soon and prints out his vector, leaving 1 out of 11 of those "Incoming connection" messages absent. There is probably something terribly wrong with the last iteration of my loop, but I can't seem to find what exactly.. Now the program just loops waiting to process the last connection.
public class VectorClockClient implements Runnable {
/*
* Attributes
*/
/*
* The client number is store to provide fast
* array access when, for example, a thread's own
* clock simply needs to be incremented.
*/
private int clientNumber;
private File configFile, inputFile;
int[] vectorClock;
/*
* Constructor
* #param
* - File config
* - int line
* - File input
* - int clients
*/
public VectorClockClient(File config, int line, File input, int clients) {
/*
* Make sure that File handles aren't null and that
* the line number is valid.
*/
if (config != null && line >= 0 && input != null) {
configFile = config;
inputFile = input;
clientNumber = line;
/*
* Set the array size to the number of lines found in the
* config file and initialize with zero values.
*/
vectorClock = new int[clients];
for (int i = 0; i < vectorClock.length; i++) {
vectorClock[i] = 0;
}
}
}
private int parsePort() {
int returnable = 0;
try {
FileInputStream fstream = new FileInputStream(configFile.getName());
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = "";
for (int i = 0; i < clientNumber + 1; i++) {
strLine = br.readLine();
}
String[] tokens = strLine.split(" ");
returnable = Integer.parseInt(tokens[1]);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("[" + clientNumber + "] returned with " + returnable + ".");
return returnable;
}
private int parsePort(int client) {
int returnable = 0;
try {
FileInputStream fstream = new FileInputStream(configFile.getName());
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = "";
for (int i = 0; i < client; i++) {
strLine = br.readLine();
}
String[] tokens = strLine.split(" ");
returnable = Integer.parseInt(tokens[1]);
}
catch (Exception e) {
e.printStackTrace();
}
return returnable;
}
private int parseAction(String s) {
int returnable = -1;
try {
FileInputStream fstream = new FileInputStream(configFile.getName());
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String[] tokens = s.split(" ");
if (!(Integer.parseInt(tokens[0]) == this.clientNumber + 1)) {
return -1;
}
else {
if (tokens[1].equals("L")) {
vectorClock[clientNumber] += Integer.parseInt(tokens[2]);
}
else {
returnable = Integer.parseInt(tokens[2]);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return returnable;
}
/*
* Do the actual work.
*/
public void run() {
try {
InitClients.barrier.await();
}
catch (Exception e) {
System.out.println(e);
}
int port = parsePort();
String hostname = "localhost";
String strLine;
ServerSocketChannel ssc;
SocketChannel sc;
FileInputStream fstream;
DataInputStream in;
BufferedReader br;
boolean eof = false;
try {
ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(hostname, port));
ssc.configureBlocking(false);
fstream = new FileInputStream("input_vector.txt");
in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
try {
InitClients.barrier.await();
}
catch (Exception e) {
System.out.println(e);
}
while (true && (eof == false)) {
sc = ssc.accept();
if (sc == null) {
if ((strLine = br.readLine()) != null) {
int result = parseAction(strLine);
if (result >= 0) {
//System.out.println("[" + (clientNumber + 1)
//+ "] Send a message to " + result + ".");
try {
SocketChannel client = SocketChannel.open();
client.configureBlocking(true);
client.connect(
new InetSocketAddress("localhost",
parsePort(result)));
//ByteBuffer buf = ByteBuffer.allocateDirect(32);
//buf.put((byte)0xFF);
//buf.flip();
//vectorClock[clientNumber] += 1;
//int numBytesWritten = client.write(buf);
String obj = Integer.toString(clientNumber+1);
ObjectOutputStream oos = new
ObjectOutputStream(
client.socket().getOutputStream());
oos.writeObject(obj);
oos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
else {
eof = true;
}
}
else {
ObjectInputStream ois = new
ObjectInputStream(sc.socket().getInputStream());
String clientNumberString = (String)ois.readObject();
System.out.println("At {Client[" + (clientNumber + 1)
+ "]}Incoming connection from: "
+ sc.socket().getRemoteSocketAddress()
+ " from {Client[" + clientNumberString + "]}");
sc.close();
}
try {
InitClients.barrier.await();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
printVector();
}
private void printVector() {
System.out.print("{Client[" + (clientNumber + 1) + "]}{");
for (int i = 0; i < vectorClock.length; i++) {
System.out.print(vectorClock[i] + "\t");
}
System.out.println("}");
}
}
To clarify, here are the formats of the files used. Config contains hostnames and ports used by clients that are threads and input file's rows mean either "this client sends a message to that client" or "this client increments his logical clock by some constant value".
1 M 2 (M means sending a message)
2 M 3
3 M 4
2 L 7 (L means incrementing clock)
2 M 1
...
127.0.0.1 9000
127.0.0.1 9001
127.0.0.1 9002
127.0.0.1 9003
...
I would look at the logic related to when you are expecting an incoming socket connection. From your question it looks like you expect a certain number of incoming socket connections (potentially an incoming connection after every outgoing message?). Since you are using non-blocking I/O on the incoming socket it is always possible that your while statement loops before an incoming socket could be established. As a result, a thread would be able to continue and read the next line from the file without receiving a connection. Since your end state is reached once the end of the file is reached, it is possible that you may miss an incoming socket connection.
I would add some simple print outs that displays when you read from the file, when you send a message and when you receive an incoming connection. That should quickly tell you whether or not a particular thread is missing an expected incoming connection. If it turns out that the problem is due to the non-blocking I/O, then you may need to disable non-blocking I/O when you expect an incoming socket or implement a control that keeps track of how many incoming sockets you expect and continues until that goal is met.
Hope this helps.

Categories