Java: Determining when a TCP Socket slows down and reestablish a connection - java

I am sending data from my system to third party systems using a persistent TCP Socket. It works fine but sometimes due to some bug in the third party system the connection slows down and it slows down my application.
How to catch this state? Should i just set a connection timeout? Because when this happens i need to close the existing socket and reestablish a new one after some period of time.
The code is as follows:
public static void initializeCongServer() throws Exception {
try{
Calendar currentTime = Calendar.getInstance();
if(congestionDownStartTime!=null){
long timeInSecs = (currentTime.getTimeInMillis() - congestionDownStartTime.getTimeInMillis())/1000;
if(timeInSecs < config.getCongestionReconnectTimeInSecs()){
logWrapper1.log(Level.DEBUG, "Packet not sent to Congestion as it was down when last checked. Connection to congestion will be retried again in: "+ (config.getCongestionReconnectTimeInSecs() - timeInSecs)+" seconds");
return;
}
}
if(congConnector!=null){
congConnector.close();
if(congConnector.sock!=null){
congConnector.sock.close();
}
congConnector = null;
}
logWrapper1.log(Level.DEBUG, "Reconnecting with congestion server.");
congConnector = new Connector(config.getCongServerIP(), config.getCongServerPort(), 1, 2);
congConnector.connect();
congestionDownStartTime = null;
} catch(Exception e){
congestionDownStartTime = Calendar.getInstance();
logWrapper1.log(Level.DEBUG, e.getMessage());
e.printStackTrace();
}
}
public static void sendDataToCongServer(String data){
try {
System.out.println("CONGESTION: "+data);
synchronized(Main.class){
if(congConnector!=null && congConnector.connected==true){
congConnector.send(data, false, false, 1);
}else{
initializeCongServer();
}
}
} catch (Exception ex) {
congestionDownStartTime = Calendar.getInstance();
logWrapper1.log(Level.DEBUG, "CONGESTION DOWN: "+data);
logWrapper1.log(Level.DEBUG, ex.getMessage());
}
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class Connector {
String host = null;
int port = 0;
int index = 0;
long reconnectTime = 0;
Socket sock = null;
boolean connected = false;
InputStream inputStream = null;
OutputStream outputStream = null;
BufferedReader bufferedReader = null;
DataOutputStream dataOutputStream = null;
public Connector(String host, int port, int index, long reconnectTime) throws Exception {
this.host = host;
this.port = port;
this.index = index;
this.reconnectTime = reconnectTime;
}
public synchronized Socket reconnect() throws Exception {
sock = new Socket(host, port);
inputStream = sock.getInputStream();
outputStream = sock.getOutputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
dataOutputStream = new DataOutputStream(outputStream);
connected = true;
return sock;
}
public void close() {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ex) {
//Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
//Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
}
}
private synchronized void notifyWait() {
connected = false;
}
public synchronized void connect() throws Exception {
reconnect();
}
public void send(String str, boolean appendLine, boolean bindResult, int MedReadTimeOut) throws Exception {
String result = null;
if (connected == true) {
try {
byte[] b = null;
if (appendLine == true) {
b = (str + "\r\n").getBytes();
} else {
b = str.getBytes();
}
dataOutputStream.write(b, 0, b.length);
dataOutputStream.flush();
} catch (IOException ex) {
notifyWait();
connected = false;
throw new Exception(ex);
}
if (bindResult == true) {
try {
sock.setSoTimeout(MedReadTimeOut);
result = bufferedReader.readLine();
}
catch (SocketTimeoutException sockEx) {
String debugInfo = "TIMEOUT= "+MedReadTimeOut+".MEDIATION PORT CLOSED " + sock.getPort();
System.out.println(debugInfo);
}
catch (IOException ex) {
//Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
notifyWait();
throw new Exception(ex);
}
}
} else {
throw new Exception("Congestion Socket Closed.");
}
}
}

A connection timeout won't help since it defines the maximum allowable time to initiate a connection. If anything, you might want to try setSoTimeout() instead.
But generally speaking, catching such a situation using socket timeouts isn't optimal, as the socket won't time out for as long as some information arrives once in a while, even it's a single byte at a time.
For a more robust solution, I suggest solving the problem at the application level, not the socket level. Maybe use a moving average to check the amount of data received/sent through the troublesome socket within a given timeframe (e.g. last 5 minutes), then reconnect if the average drops below a predefined threshold.

Related

Java socket programming fails to close the connection gracefully [duplicate]

I have written a program given below. It accept some data from client & returns success in response. Sometimes it throws connection reset error & due to which some socket connection remain unclose result. Any idea how to handle connection reset error when client code tries to communicate & connection is closed by client automatically?
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class tcp_server implements Runnable {
private final Socket server;
private PrintWriter toClient = null;
private BufferedReader fromClient = null;
public tcp_server(Socket s) {
this.server = s;
}
#Override
public void run() {
String name = "";
synchronized (server) {
try {
server.setSoTimeout(6000);
toClient
= new PrintWriter(server.getOutputStream(), true);
fromClient
= new BufferedReader(
new InputStreamReader(server.getInputStream()));
String line = "";
String data = "";
while ((line = fromClient.readLine()) != null) {
data = data + line;
toClient.println("{status:success}");
break;
}
} catch (Exception eb) {
System.out.println("{status:error,Reason:" + eb.getMessage() + "}");
} finally {
// System.out.println("Finally not called if timeout occurs");
if (toClient != null) {
toClient.close();
}
if (fromClient != null) {
try {
fromClient.close();
} catch (IOException ex) {
Logger.getLogger(tcp_server.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
server.close();
} catch (IOException ex) {
Logger.getLogger(tcp_server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String[] args) throws IOException {
int serverPort = 40820;
ServerSocket serverSocket = new ServerSocket(serverPort);
synchronized (serverSocket) {
for (;;) {
Socket server = serverSocket.accept();
new Thread(new tcp_server(server)).start();
}
}
}
}
This is better code ... but still with same error "Connection reset" though applied timeout to 60sec
You handle it by closing the connection, of course.
The real question is why did you get it? There are several common causes:
you wrote to a connection that had already been closed by the peer
you closed a connection without reading data that had already arrived in the socket receive buffer. This will reset the peer.
Both of these are application protocol errors that should be fixed. There isn't any point in sending data that won't be read.

How to tell the Browser that the data that its getting is html and not regular text?

I wrote a Java server application that returns a file when it is requested by a browser. The browser makes a GET request to my socket and the socket returns the file. But the browser (firefox in my case) treats the html file as a regular text file and does not render the actual page. So the browser shows the whole html source code. How can I fix that?
Here the Code:
package ml.mindlabor.networking;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
static final int PORT = 9806;
static final int MAX_BYTES_PER_STREAM = 10_000; // 10 kB
static final String FILE_SYSTEM_PATH = "C:\\Users\\SBrau\\eclipse-workspace\\Networking\\src\\ml\\mindlabor\\networking\\Files\\public_html";
static boolean running = true;
ServerSocket ss = null;
Socket soc = null;
public static void main(String[] args) {
Server server = new Server();
// When the connection could not be established
System.out.println("Waiting for connection ...");
if (!server.connect()) return;
server.listenForResponse();
}
public Server() {
try {
ss = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Could not create ServerSocket on Port " + PORT);
shutdown();
}
}
boolean respond(String response) {
try {
PrintWriter out = new PrintWriter(soc.getOutputStream(), true);
out.println(response);
return true;
} catch (IOException e) {
System.err.println("Could not send to Port " + PORT);
}
return false;
}
boolean respond(byte[] response) {
try {
soc.getOutputStream().write(response);
return true;
} catch (IOException e) {
System.err.println("Could not send to Port " + PORT);
}
return false;
}
boolean respondFile(String relPath) {
String path = Server.FILE_SYSTEM_PATH + relPath;
File file = new File(path);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[(int)file.length()]; // or 4096, or more
in.read(buffer, 0, buffer.length);
soc.getOutputStream().write(buffer, 0, buffer.length);
System.out.println("Loaded :D");
in.close();
soc.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
String rawDataToString(byte[] rawData) {
return new String(rawData);
}
void listenForResponse() {
new Thread(() -> {
while (true) {
try {
DataInputStream in = new DataInputStream(soc.getInputStream());
byte[] packetData = new byte[MAX_BYTES_PER_STREAM];
in.read(packetData);
receivedPackage(packetData);
} catch (IOException e) {
System.err.println("Could not get data from port " + PORT);
shutdown();
}
}
}).start();
}
void shutdown() {
Server.running = false;
}
void receivedPackage(byte[] pkg) {
String request = new String(pkg).trim();
// GET Request for file
if (request.contains("GET ")) {
String[] arr = request.split(" ");
respondFile(arr[1].trim());
}
}
boolean connect() {
try {
soc = ss.accept();
//soc.setKeepAlive(true);
System.out.println("Connected!");
return true;
} catch (IOException e) {
System.err.println("Could not wait for connection on port " + PORT);
shutdown();
}
return false;
}
}
Ok. Got it. I solved it by rewriting the following method:
boolean respondFile(String relPath) {
String path = Server.FILE_SYSTEM_PATH + relPath;
File file = new File(path);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
PrintWriter out = new PrintWriter(soc.getOutputStream());
BufferedOutputStream dataOut = new BufferedOutputStream(soc.getOutputStream());
byte[] fileData = readFileData(file, (int)file.length());
out.println("HTTP/1.1 501 Not Implemented");
out.println("Content-type: text/html");
out.println(); // blank line between headers and content, very important !
out.flush();
dataOut.write(fileData, 0, fileData.length);
dataOut.flush();
System.out.println("Loaded :D");
in.close();
soc.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];
try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}
return fileData;
}

Eliminate Half Strings when receiving from Server socket Buffer in JAVA

I have written a simple NIO Server and Inner-Client (Inside the same program)in a single program such that Server receives data from outside and the Inner-Client sends the data received by the server to out side Server. I am running both the processes continuously in two parallel threads using While() loops. Now the problem is, I will be receiving data at a very high speed to the Inside server and everything I receive, I will send them to the outer server using the Inside client. Some times, the retrieval of the data from the Buffer resulting in half the size of the total string. That means I am receiving "HELLO", but the total string is "HELLO SERVER". This is just an example. I will receive very long strings. Similarly, after sending the data to Outer-server through Inner client I will be listening for data and I am receiving the same half-strings.Is there any way I can eliminate these Half-strings and get the full-length string. I have to get the full string without any fail.
I am using while loops for the process. This is making the CPU utilization go high like 50%. Is there any way I can reduce the CPU utilization without using Thread.sleep method? Because I need to continuously listen to data from the Outer parties. They may send 2-4 strings for one single request. I tried using Executor service thread for running the processes continuously but it requires some sleep to be included. If I include some sleep I am not able to get the String and if I don't include the sleep my CPU-Utilization is going very high (50-60%). Can anyone help me with these two issues?
Here is my code:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
static SocketChannel channel;
public static void main(String[] args) throws IOException {
System.out.println("Listening for connections on : 8888"); //8888
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(8888));
channel = serverChannel.accept();
System.out.println("Connected...");
channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
channel.configureBlocking(false);
ReceiveFromOMS receivefromOMS;
SendToExchange sendExchange;
receivefromOMS = new ReceiveFromOMS();
sendExchange = new SendToExchange();
Thread t1 = new Thread(receivefromOMS);
Thread t2 = new Thread(sendExchange);
t1.start();
t2.start();
}
}
class ReceiveFromOMS extends Thread{
public static SocketChannel channel;
static ByteBuffer buffer = ByteBuffer.allocate(1024);
static ServerSocketChannel serverChannel ;
public static int ReceiveFromOMSPort;
BlockingQueue<String> fromOMSqueue = new LinkedBlockingQueue<>(30);
#Override
public void run(){
while(true){
try {
receiveFromOMS();
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
try {
Thread.sleep(5000);
} catch (InterruptedException ex1) { }
}
}
}
public void receiveFromOMS() throws InterruptedException{
try {
int numRead = -1;
numRead = channel.read(buffer);
while(numRead==0){
numRead = channel.read(buffer);
}
if (numRead == -1) {
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
System.out.println("Connection closed by client: " + remoteAddr);
channel.close();
return;
}
byte[] data = new byte[numRead];
System.arraycopy(buffer.array(), 0, data, 0, numRead);
fromOMSqueue.add(new String(data));
String msg = fromOMSqueue.poll();
System.out.println("OutGoing To Exchange>> " + msg);
SendToExchange.sendToEchange(msg);
buffer.flip();
buffer.clear();
} catch (IOException ex) {
System.err.println(ex.getMessage());
Thread.sleep(5000);
}
}
}
class SendToExchange extends Thread{
static SocketChannel channel;
static ByteBuffer bb = ByteBuffer.allocateDirect(1024);
static Charset charset = Charset.forName("UTF-8");
public byte[] data;
public static String message;
#Override
public void run(){
try {
while(true){
receive();
Thread.sleep(100);
}
} catch (IOException | InterruptedException ex) {
System.err.println(ex.getMessage());
try {
Thread.sleep(5000);
} catch (InterruptedException ex1) {}
}
}
public static void sendToEchange(String msg){
try {
bb = stringToByteBuffer(msg, charset);
channel.write(bb);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public void receive() throws IOException {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
int numRead = -1;
numRead = channel.read(buffer);
while (numRead == 0) {
numRead = channel.read(buffer);
}
if (numRead == -1) {
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
System.out.println("Connection closed by Exchange: " + remoteAddr);
channel.close();
return;
}
buffer.flip();
data = new byte[numRead];
buffer.get(data);
message = new String(data);
System.out.println("Incoming from Exchange>> " + message);
buffer.clear();
}
public static ByteBuffer stringToByteBuffer(String msg, Charset charset){
return ByteBuffer.wrap(msg.getBytes(charset));
}
}
Lets assume that your server is appending to each string an End of message marker string, e.g. "<EOM>", then the following modification of your code (treat it as a sketch since I did not verified it completely) can be used to wait for the full string:
String end = "<EOM>";
StringBuilder curStr = new StringBuilder();
int numRead = 0;
while(-1 != (numRead = channel.read(buffer))){
curStr.append(new String(buffer.array(), 0, numRead, Charset.forName("UTF-8")));
int endIdx = curStr.indexOf(end);
if (endIdx != -1) {
fromOMSqueue.add(curStr.substring(0, endIdx + end.length()));
break;
}
}
if (numRead == -1) {
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
System.out.println("Connection closed by client: " + remoteAddr);
channel.close();
return;
}
String msg = fromOMSqueue.poll();

Socket Issue - Only first message read

I am very new to sockets and was hoping someone could help me. I had something working but it was not sending information very quickly so i have refactored and now cannot get back to anything which works. The issue seems to be that only the first message that is published is read and then the receiver sits on client = listener.accept(); even though im pretty sure the sender is still sending messages
Can anyone see what i might be doing wrong here please?
Thanks
public class Sender {
Socket server = null;
DataInputStream inp = null;
PrintStream outp = null;
public Sender(){
server = new Socket("127.0.0.1" , 3456);
outp = new PrintStream(server.getOutputStream());
}
private void connectAndSendToServer(String message) {
outp = new PrintStream(server.getOutputStream());
outp.print(message + "\n");
outp.flush();
}
}
Receiver class
public class Receive{
public String receiveMessage(int port) {
String message= null;
ServerSocket listener = null;
Socket client = null;
try{
listener = new ServerSocket(port);
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
return br.readLine();
}
...
finally{
try {
if(client!=null && listener!=null){
client.close();
listener.close();
}
}
catch (IOException e) {
}
}
return message;
}
}
This because a ServerSocket is used as an entry point for a normal Socket. accept() is a blocking operation that is usually done on a different thread compared to the one that receives/sends data to normal Socket. It sits there and waits for a new connection to spawn a new Socket which is then used for data.
This means that while receiving messages you should call just readLine() to read from the specific Socket. Having an accept inside the receiveMessage is wrong just because it's a different operation and it's even blocking.
Socket socket = serverSocket.accept();
ClientThread thread = new ClientThread(socket);
class ClientThread extends Thread {
Socket socket;
public void run() {
while (!closed) {
String line = reader.readLine();
...
}
}
You don't need to have a thread for every client though, but you need at least two for sure if you want to make your server accept a number of connections greater than 1.
You are not using ServerSocket correctly. You shouldn't create a new instance for every message but use it as a data member maybe and run an infinite loop to get a new client socket connection. Because you create it locally, the socket is closed since the object is no longer used and referenced (and so GC'ed), when you return from the method.
Something like (< condition met > is pseudo-code defines your condition to accept new connections):
while(< condition met >) {
try {
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = br.readLine();
//do something with str
} finally {
//close client socket
}
}
Better approach will be to handle client socket in a different thread so the main thread is back to accept while you can do anything with the client socket in parallel.
Try this basic Chatting Server written by me. This server simply keeps running in loop and broadcast the message send by the clients to all the other clients associated with this server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
// ///----------------------------------------Instance Variable Fields
ServerSocket ss = null;
Socket incoming = null;
// ///----------------------------------------Instance Variable Fields
// ///---------------------------------------- static Variable Fields
public static ArrayList<Socket> socList = new ArrayList<Socket>();
// ///---------------------------------------- static Variable Fields
public void go() {
try {
ss = new ServerSocket(25005);
while (true) {
incoming = ss.accept();
socList.add(incoming);
System.out.println("Incoming: " + incoming);
new Thread(new ClientHandleKaro(incoming)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandleKaro implements Runnable {
InputStream is = null;
OutputStream os = null;
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean isDone = false;
Socket sInThread = null;
public ClientHandleKaro(Socket sxxx) {
this.sInThread = sxxx;
}
#Override
public void run() {
if (sInThread.isConnected()) {
System.out.println("Welcamu Clienta");
System.out.println(socList);
}
try {
is = sInThread.getInputStream();
System.out.println("IS: " + is);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = sInThread.getOutputStream();
pw = new PrintWriter(os, true);
String s = new String();
while ((!isDone) && (s = br.readLine()) != null) {
String[] asx = s.split("-");
System.out.println("On Console: " + s);
// pw.println(s);
Thread tx = new Thread(new ReplyKaroToClient(s,
this.sInThread));
tx.start();
if (asx[1].trim().equalsIgnoreCase("BYE")) {
System.out.println("I am inside Bye");
isDone = true;
}
}
} catch (IOException e) {
System.out.println("Thanks for Chatting.....");
} finally {
try {
Thread tiku = new Thread(new ByeByeKarDo(sInThread));
tiku.start();
try {
tiku.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Accha to hum Chalte hain !!!");
System.out.println(socList);
br.close();
pw.close();
sInThread.close();
} catch (IOException e) {
}
}
}
}
class ReplyKaroToClient implements Runnable {
public String mString;
public Socket mSocket;
public ReplyKaroToClient(String s, Socket sIn) {
this.mString = s;
this.mSocket = sIn;
}
#Override
public void run() {
for (Socket sRaW : socList) {
if (mSocket.equals(sRaW)) {
System.out.println("Mai same hun");
continue;
} else {
try {
new PrintWriter(sRaW.getOutputStream(), true)
.println(mString);
} catch (IOException e) {
System.out.println("Its in Catch");
}
}
}
}
}
class ByeByeKarDo implements Runnable {
Socket inCom;
public ByeByeKarDo(Socket si) {
this.inCom = si;
}
#Override
public void run() {
try {
new PrintWriter(inCom.getOutputStream(), true)
.println("You have Logged Out of Server... Thanks for your Visit");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server().go();
}
}

Java Sockets for communication with IRC server

I am learning Java and want to create my own IRC client. I have two threads but the problem is that I do not always get a response from server (can't see PING) and it lags for my message to be delivered.
I thought it was related to thread not having a sleep, but it turns out it's not.
When I connect to the server I send the following commands to identify myself and privatemsg self:
USER me * 8 : hi
NICK mynick
I am also not sure if my usage of threads is correct.
The code I used:
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class f_irc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Socket ircSocket = null;
BufferedWriter out = null;
BufferedReader in = null;
String host = "irc.freenode.net";
int port = 6667;
Boolean proxyEnabled = true;
try {
SocketAddress addr = new InetSocketAddress("127.0.0.1", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
ircSocket = new Socket(proxy);
InetSocketAddress final_addr = new InetSocketAddress(host, port);
ircSocket.connect(final_addr);
}
catch(Exception e)
{
ircSocket = new Socket(host, port);
}
Thread listener = new ServerListener(ircSocket);
listener.start();
System.out.println("Listener started!");
Thread sender = new ServerSender(ircSocket);
sender.start();
System.out.println("Sender started!");
}
}
class ServerListener extends Thread implements Runnable {
Socket ircSocket;
String serverAnswer = null;
BufferedReader in = null;
ServerListener(Socket irc) throws IOException {
ircSocket = irc;
in = new BufferedReader(new InputStreamReader(irc.getInputStream()));
}
#Override
public void run() {
while(true) {
System.out.println("Running: ");
try {
serverAnswer = in.readLine();
if (serverAnswer != null) {
System.out.println("Server talkin: " + in.readLine());
System.out.println("Server talkin++: " + serverAnswer);
}
} catch (IOException ex) {
System.out.println("cant read linez br0w");
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ServerSender.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
class ServerSender extends Thread {
Socket ircSocket;
String serverCommand = null;
BufferedWriter out = null;
BufferedReader stdIn = null;
ServerSender(Socket irc) throws IOException {
ircSocket = irc;
out = new BufferedWriter(new OutputStreamWriter(irc.getOutputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
}
#Override
public void run() {
while(true) {
System.out.println("Running snder: ");
try {
serverCommand = stdIn.readLine();
if (serverCommand != null) {
out.write(serverCommand + "\n");
out.flush();
System.out.println("Sent: " + serverCommand);
}
}
catch(IOException e) {
System.out.println("Server fed up");
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
System.out.println("Sleep failed!");
}
}
}
}
you are calling in.readLine() twice in your ServerListener. since you are consuming 2 messages per-loop, will not see any output until you get an even number of messages (so the 3rd message will seem to "hang" until you get the fourth).

Categories

Resources