Java Messaging System - java

I am creating a Java file send program. Right now I am attempting to implement a chat messaging system.
Here is the code for calling the Server/Client code:
if(host.isSelected()) {
Server server = new Server();
ServerChat serverChat = new ServerChat();
server.Thread();
serverChat.Thread();
}
else if(guest.isSelected()) {
Client client = new Client();
ClientChat clientChat = new ClientChat();
client.Thread();
clientChat.Thread();
}
This calls the code in the following classes: ServerChat
public class ServerChat extends Main implements Runnable {
public static ServerSocket ss;
public static Socket s;
public static DataInputStream dis;
public static DataOutputStream dos;
public void Thread() {
(new Thread(new ServerChat())).start();
}
#Override
public void run() {
String variable = "";
try {
ss = new ServerSocket(1234);
s = ss.accept();
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
while (!variable.equals("exit")) {
variable = dis.readUTF();
chatText.setText(chatText.getText().trim() + "\n Client:\t" + variable);
}
} catch (Exception e) {
}
if (send.isSelected()) {
try {
String messageOut = "";
messageOut = chatText.getText().trim();
dos.writeUTF(messageOut);
} catch (Exception e) {
}
}
}
}
ClientChat code:
public class ClientChat extends Main implements Runnable {
public void Thread() {
(new Thread(new ClientChat())).start();
}
#Override
public void run() {
try {
socket = new Socket("localhost", 1234);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
String variable = "";
while (!variable.equals("exit")) {
variable = dis.readUTF();
chatText.setText(chatText.getText().trim() + "\n Server:\t" + variable);
}
} catch (Exception e) {
}
if (send.isSelected()) {
try {
String messageOut = "";
messageOut = chatText.getText().trim();
dos.writeUTF(messageOut);
} catch (Exception e) {
}
}
}
}
They are able to connect to each other, but the data is not being posted into the text boxes which I have created in the main class. (All the elements needed from main are public).
When I connect (via locahost) I create the server through a new class and open up a new thread
public class Server extends Main implements Runnable {
public ServerSocket welcomeSocket;
public String file;
public DataOutputStream dos;
public DecimalFormat df = new DecimalFormat("##, #00");
public BufferedReader inFromClient;
public void Thread() {
(new Thread(new Server())).start();
}
#Override
public void run() {
try {
InetAddress localaddr = InetAddress.getLocalHost();
chatText.append("Local IP Address : " + localaddr);
chatText.append("Local hostname : " + localaddr.getHostName());
String clientSentence = null;
String capitalizedSentence;
welcomeSocket = new ServerSocket(1234);
String file = "";
DecimalFormat df = new DecimalFormat("##, #00");
while (true) {
Socket connectionSocket = welcomeSocket.accept();
inFromClient
= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
} catch (Exception e) {
chatText.append("Unable to create server");
chatText.append("Can't detect local host : " + e);
}
}
The Same goes for the Client:
public class Client implements Runnable {
public DataOutputStream dos;
public DataInputStream dis;
public Socket skt;
public StringTokenizer st;
public void Thread() {
try {
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
} catch (Exception e) {
System.out.println(e.getMessage());
}
(new Thread(new Client())).start();
}
#Override
public void run() {
try {
InetAddress localaddr = InetAddress.getLocalHost();
skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
while (!Thread.currentThread().isInterrupted()) {
String data = dis.readUTF();
st = new StringTokenizer(data);
String CMD = st.nextToken();
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File f = open.getSelectedFile();
String fileName = f.getAbsolutePath();
FileInputStream fs = new FileInputStream(fileName);
switch (CMD) {
case "CMD_SENDFILE":
try {
fileName = st.nextToken();
System.out.println("Receiving file...");
String path = System.getProperty("user.home");
File file = new File(path + "/Downloads" + fileName + ".txt");
FileOutputStream fos = new FileOutputStream(path);
InputStream input = skt.getInputStream();
byte[] buffer = new byte[1024];
int count, percent = 1;
while ((count = input.read(buffer)) > 0) {
percent = percent + 1;
fos.write(buffer, 0, count);
}
fos.close();
System.out.println("File was saved: " + path);
} catch (Exception e) {
DataOutputStream eDos = new DataOutputStream(skt.getOutputStream());
System.out.println(e.getMessage());
skt.close();
}
break;
}
}
/*String string = in.readLine();
System.out.println("Incoming: " + string + "\n");
System.out.println("Incoming: " + in.readLine() + "\n");
//in.close();*/
} catch (Exception e) {
System.out.println("Error could not connect\n");
}
}
}

Your main problem is here:
public class ClientChat extends Main implements Runnable {
You're mis-using inheritance. Inheritance is not used so that one instance can share variables with another, which is what you're trying to use it for. Instead it's mainly used to share behaviors. I strongly urge that ClientChat not extend Main but rather has a Main field, one whose public methods it can call.
Your other two problems are lesser problems, but they still will cause you headaches:
You generally want to avoid ignoring exceptions as you're doing. At least have the catch block print the stacktrace: e.printStackTrace();.
You will want to be sure that Swing calls, including calls to setText(...) on text components, be made on the Swing event thread. If you're using a plain vanilla thread, then this can be done via SwingUtilities.invokeLater(new Runnable() {...});. Otherwise consider using a SwingWorker which will help automate this for you with its publish / process method pair.
You've asked:
About inheritance, is there any post I can look at for calling main fields for the ClientChat?
Look up "inheritance vs composition" -- you would be using the latter, composition here, not inheritance.
You would likely want to pass information back and forth between the GUI, or "view" portion of your code, with the chat engine or "model" portion of your code. There are several ways to do that, but usually they'd be connected by some type of "control" class or classes, something known as the "MVC" or "Model-View-Controller" architecture.

Related

Java Server and Client in one program

i want to synchronize 2 Collections with each other. If something changes at the Server side, the connected Clients get updated.
I have a quite basic question. Do I now need to copy my java project and program the server in one and the client in the other one? But that sounds like quite a lot of unnecessary work. Can't I implement it all in one project an then start server and client in one main? Do I need threads? I'm kind of stuck what the best way is here.
Thanks in advance.
Because codereview doesn't allow my code cause it's not yet working, i post it now here in the hope, that you can help me.
public class Server implements Runnable{
private String hostName = "127.0.0.1";
private int portNumber;
private ServerSocket serverSocket;
private Socket clientSocket;
public Server(int port){
this.portNumber = port;
}
public void run(){
String line = "";
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
try{
this.serverSocket = new ServerSocket(this.portNumber);
}catch (IOException e) {
System.out.println("Could not listen on port");
}
try{
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed");
}
try{
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
}catch (IOException e) {
System.out.println("Read failed");
}
while(true){
try{
line = in.readLine();
}catch (IOException e) {
System.out.println("Read failed");
}
System.out.println("line: "+line);
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
serverSocket.close();
}catch (IOException e) {
System.out.println("Could not close socket");
}
}
}
public class Client implements Runnable{
private String hostName = "127.0.0.1";
private int portNumber = 6602;
private Socket clientSocket = null;
public Client(Socket client){
this.clientSocket = client;
}
public Client(int portNumber, String hostName){
this.portNumber = portNumber;
this.hostName = hostName;
}
public void run(){
String line;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
try{
if(clientSocket == null)
this.clientSocket = new Socket(this.hostName, this.portNumber);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
out.println("Test string from client");
}catch (IOException e){
System.out.println("in or out failed");
}
}
}
public class DebugServerClient {
public static void testServerClient(){
int port = 6602;
Server srv = new Server(port);
Client clt = new Client(port, "127.0.0.1");
Thread s = new Thread(srv);
s.start();
Thread c = new Thread(clt);
c.start();
}
}
I changed it now to this and it seems to work. Is this a good way?

How to make two seperate clients share the same data from the server?

I have this server and client application that counts how many times a button has been clicked. Some other members here were kind enough to solve my previous issue with it, and now I have another.
When I start up the server, and a client connects, and the client clicks the button, the counter on the server side goes up. However, when a second client connects to the server, the counter resets to 0. I am thinking that the server creates a seperate instance of the counter for some reason.
Here is the (updated) server sided code:
public class Server {
public static void main(String[] args) throws Exception {
Socket socket = null; //create a new socket
ServerSocket listener = new ServerSocket(9898);
System.out.println("The server is running!");
try {
while (true) {
new ClickServer(listener.accept()).start();
}
} finally {
listener.close();
}
}
/**
* A private thread to handle clicking requests
*/
private static class ClickServer extends Thread {
private Socket socket;
AtomicInteger totalBets = new AtomicInteger(0);
public void incrementTotalBets() {
totalBets.incrementAndGet();
}
public int getTotalBets() {
return totalBets.get();
}
public ClickServer(Socket socket) {
this.socket = socket;
log("New connection with client at " + socket);
}
public void run() {
try {
while (true) {
socket.setTcpNoDelay(true);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String input = br.readLine();
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
if(input.equals("increment")) {
bw.write(String.valueOf(totalBets.incrementAndGet()));
bw.newLine();
bw.flush();
System.out.println("Total Bets: " + getTotalBets());
}
}
} catch (IOException e) {
log("Error handling client\n" + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Error closing socket");
}
log("Connection with client closed");
}
}
private void log(String message) {
System.out.println(message);
}
}
}
The totalBets integer is the counter. When multiple client join the server, and click the button, it should increment the counter and send it back based on what the counter already is. It shouldn't reset for every new client.
Here is the relevant client-sided code:
public void actionPerformed(ActionEvent arg0) {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String target = "";
bw.write("increment" + "\n");
bw.flush();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String id = br.readLine();
System.out.println("bet added: " + id);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I'm not sure why a new instance of the Server is being created every time a new client connects. I did some debugging, and the server knows there is more than one client connected to the server at the same port.
Any help?
Thank you.
NOTE: the ClickServer class is nested inside the Server class. It just doesn't look that way in the code box.
You'd need a shared counter that's thread safe. I'd go for
public static AtomicInteger totalBets = new AtomicInteger (0);
You'd have to change getter and setter some but this should share value between Clients. Or trash those methods and simply do
if(input.equals("increment")) {
bw.write(String.valueOf(totalBets.incrementAndGet ()));
Try changing :
public int totalBets = 0;
to:
public static int totalBets = 0;

Getting data from socket on Android

So I have this really, really strange problem with getting data using socket from server which is working on my PC to Android app. All in local network for now.
It is strange, because I wrote server and client apps (both using sockets) to send and get data and it works really great. I tried to do exactly the same on Android and it gets only first response from server, but not the rest after sending token.
I searched through SO and saw piece of advice that available() method is not right so I changed it and it's still not working as I wish it would.
I think there is something wrong with server-side app or android app works way too fast for server and it sends data after ending transmission on android, but I tried to give it a bit of time and nothing...
This is server app (in general it gets token, lets say "RAM" then it gets output from linux process and sends it straight to android app):
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
public class BLCServer extends Thread{
private ServerSocket serverSocket;
public BLCServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(86400000);
}
public void run() {
while(true) {
try {
String token = "";
System.out.println("Waiting for a client on port: "+serverSocket.getLocalPort());
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
System.out.println("Beginning transmission");
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thanks for connecting to " + server.getLocalSocketAddress() + "Goodbye\n");
while(token != "END") {
token = in.readUTF();
if(token.equals("RAM")) {
Ram ram = new Ram();
List<String> ramData = new ArrayList<>();
ramData = ram.getRamData();
System.out.println("RAM");
System.out.println("ram.size(): " + ramData.size());
out.writeUTF("ramBeginning");
for(String x : ramData) {
System.out.println("Wysyłam do clienta: " + x);
out.writeUTF(""+x);
}
out.writeUTF("ramEnd");
} else if(token.equals("CPU")) {
Cpu cpu = new Cpu();
List<String> cpuData = new ArrayList<>();
cpuData = cpu.getCpuLoad();
System.out.println("CPU");
out.writeUTF("cpuBeginning");
for(String x : cpuData) {
out.writeUTF(x);
}
out.writeUTF("cpuEnd");
} else if(token.equals("STORAGE")) {
Storage storage = new Storage();
List<String> storageData = new ArrayList<>();
storageData = storage.printStorageData();
System.out.println("STORAGE");
out.writeUTF("storageBeginning");
for(String x : storageData) {
out.writeUTF(x);
}
out.writeUTF("storageEnd");
} else if(token.equals("UPTIME")) {
Uptime uptime = new Uptime();
String uptimeData = uptime.getUptime();
System.out.println("UPTIME");
out.writeUTF("uptimeBeginning");
out.writeUTF(uptimeData);
out.writeUTF("uptimeEnd");
} else if(token.equals("TEMPERATURES")) {
out.writeUTF("temperaturesBeginning");
out.writeUTF("temperaturesEnd");
} else if(token.equals("END")) {
break;
} else {
out.writeUTF("Token unknown");
}
}
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 = 1984;
try {
Thread t = new BLCServer(port);
t.start();
} catch(IOException e) {
e.printStackTrace();
}
}
}
And also there is android main activity:
public class MyActivity extends Activity {
TextView cpuT;
TextView ramT;
TextView uptimeT;
TextView storageT;
List<String> ram = new ArrayList<String>();
List<String> cpu = new ArrayList<String>();
List<String> uptime = new ArrayList<String>();
List<String> storage = new ArrayList<String>();
List<String> temperatures = new ArrayList<String>();
public class NetThread extends AsyncTask<String, Void, Void> {
String dstAddress = "192.168.0.111";
int dstPort = 1984;
#Override
protected Void doInBackground(String... args) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
InputStream inFromServer = new PushbackInputStream(socket.getInputStream());
DataInputStream in = new DataInputStream(inFromServer);
out.writeUTF("Hello from " + socket.getLocalSocketAddress());
int singleByte;
ramT.setText(in.readUTF());
out.writeUTF("RAM");
while((singleByte = inFromServer.read()) != -1) { // there was code like: while(in.available() > 0) { ... } but someone wrote about it's bad behaviour on SO
ramT.setText(ramT.getText() + "\n" + singleByte);
}
}
out.writeUTF("END");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("WEBSERVICE", "Oncreate wywołane\n");
cpuT = (TextView) findViewById(R.id.displayCpu);
ramT = (TextView) findViewById(R.id.displayRam);
uptimeT = (TextView) findViewById(R.id.displayUptime);
storageT = (TextView) findViewById(R.id.displayStorage);
NetThread netThread = new NetThread();
netThread.execute("RAM", "STORAGE", "UPTIME");
}
}
In addition I paste you client application for pc:
public class BLCClient {
public static void main(String[] args) {
String serverName = "localhost";
int port = 1984;
try {
System.out.println("Connecting to..."+serverName+" on port 1984");
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "+client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
Scanner cin = new Scanner(System.in);
String token = "";
out.writeUTF("Hello from " + client.getLocalSocketAddress());
System.out.println("Server says: "+in.readUTF());
while(true) {
System.out.println("Podaj token ciulu: ");
token = cin.nextLine();
System.out.println("Twój token: " + token);
if(token.equals("END")) {
out.writeUTF(token);
break;
} else {
out.writeUTF(token);
System.out.println(in.readUTF());
System.out.println("IN: " + in.available());
while(in.available() > 0) {
System.out.println(in.readUTF());
}
}
}
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
Yes. I'm using part of code from tutorialspoint.com. If you need classes for getting data for ram, cpu, storage, temperatures or uptime processes let me know.
For now I've spent around 4 days trying to figure out what is wrong with my code for android (because servers sends data correctly, I'm 99% sure). Please help me. I'm powerless and I want this app wake to work so so badly right now (Actually I made this work using tomcat server, but I want my own server in here).
Thanks.

Chat Application in java

I'm trying to make a chat application in java, but I had a problem, when I couldn't send to another machine.
Here's part of my codes:
This is my class client:
public class EnvioSocket {
public static boolean enviarSocket(String nome, String ip, int porta,
String mensagem) {
String dados = nome + " : " + mensagem;
try {
Socket socket = new Socket(ip, porta);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(dados);
out.close();
socket.close();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
}
return true;
}
}
This is my class server:
public class ServidorThread implements Runnable {
private JTextArea menssage;
public ServidorThread(JTextArea menssage) {
this.menssage = menssage;
}
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(Porta.PORTA);
while (true) {
Socket acceptedSocket = serverSocket.accept();
DataInputStream in = new DataInputStream(
acceptedSocket.getInputStream());
String menssage = in.readUTF();
this.menssage.append(DateUtils.dateToString(new Date(), "dd/MM/yyyy HH:mm") + " " + menssage + "\n");
in.close();
acceptedSocket.close();
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
define a port to socket
public final class Porta {
private Porta() {
}
public static final int PORTA = 6066;
}
I can only send a message to my own computer. How can I fix this?
I'm starting my thread inside of my class that make a GUI.
It looks like you've set up your Server right, but your client doesn't seem to ever connect to it. You need to create a socket which will connect to the server socket. This socket can then give you I/O streams to send data through.
Java's tutorial, complete with code examples
The question is not that simple to me...I can show you the basics for client server echo application in java...You can expand on that to make a chat session between to clients I suppose...here it goes...
public class MultiThreadServer implements Runnable {
Socket csocket;
private static boolean quitFlag = false;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (!quitFlag) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
String action = in.readLine();
PrintStream pstream = new PrintStream(csocket.getOutputStream());
System.out.printf("Server received... " + action + " ...action\n");
switch (action) {
case "bottle":
for (int i = 3; i >= 0; i--) {
pstream.println("<p>" + i + " bottles of beer on the wall" + "</p>");
}
pstream.println("<p>" + action + "</p>");
break;
case "echo":
pstream.println("<p>" + action + "</p>");
break;
case "quit":
quitFlag = true;
break;
}
pstream.close();
csocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Running the server to echo your response is easy...making the client or clients are more challenging...simple jsp Client..
<BODY>
<H1>Creating Client/Server Applications</H1>
<%
String serverInput = request.getParameter("serverInput");
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
InputStream inSocket = socket.getInputStream();
OutputStream outSocket = socket.getOutputStream();
String str = serverInput+"\n";
byte buffer[] = str.getBytes();
outSocket.write(buffer);
while ((character = inSocket.read()) != -1) {
out.print((char) character);
}
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</BODY>
or better yet...
<body>
<%String name = request.getParameter("inputString");%>
<h1>Creating Client Applications</h1>
<p>Client Sent... <%=name%> ...to Server</p>
<%
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
OutputStream outSocket = socket.getOutputStream();
String str = name;
byte buffer[] = str.getBytes();
outSocket.write(buffer);
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</body>

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