Tcp output/input doesnt work - java

I'm trying to change my game to use TCP, but I can't even get it to work.
The client connects successfully with the server, but for some reason I can't
receive messages from server nor receive messages from client. My guess is that I'm doing something wrong with the output/input?
Here is the server code:
public class Server implements Runnable {
Server() {
serverSocket = new ServerSocket(1919, 300);
}
run() {
while (true) {
String message = "blank";
try {
//w8ting for some connection
tcpSOCKET = tcpServer.accept(null);
//Connected to some1!
input = new BufferedReader(new InputStreamReader(
tcpSOCKET.getInputStream()));
output = new DataOutputStream(
tcpSOCKET.getOutputStream());
output.flush();
//TODO PROBLEM it stays here trying to read line but even if the client send a message it wont move on
message = input.readLine();
main.addLabel(Color.BLUE, message);
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the client:
public class Client implements Runnable {
Client() { }
run() {
String message = "";
try {
tcpSOCKET = new Socket(serverIp, serverTCPport);
input = new BufferedReader(new InputStreamReader(
tcpSOCKET.getInputStream()));
output = new DataOutputStream(tcpSOCKET.getOutputStream());
output.flush();
while (true) {
System.out.println("w8ting for message from server");
//TODO problem, it wont read anything even if the server send a message
message = input.readLine();
System.out.println("A message has arrived: " + message);
gameScreen.serverMessage = message;
}
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and the class is called when I hit "s" in the server or in the client, they both use the same class
public void sendTCPMessage(String message) {
try {
output.writeBytes(message);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}

If you want to read lines, you must write lines.
If you want to read with a BufferedReader, you should write with a BufferedWriter.
If you want to write with a DataOutputStream, you should read with a DataInputStream.

Related

How can i measure my local server's response time?

I am using a server-client based architecture with sockets in java on my localhost and I need to know how much it takes my localhost to send a response, any ideas on how I can measure that?
(i am using 2 separate classes for listening to the keyboard and the server at the same time)
This is my Clients main function:
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_IP,SERVER_PORT);
ServerConnection connection = new ServerConnection(socket);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
new Thread(connection).start();
while(true){
String command = keyboard.readLine();
if(command == "quit"){
break;
}
out.println(command);
}
socket.close();
System.exit(0);
}
This is my server connection class's run method where I listen to te server.
#Override
public void run() {
String res = null;
try {
while (true) {
res = in.readLine();
if (res==null) break;
System.out.println("Server>: " + res);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
so in other words I am sending the request from one class and receiving it in another class.

Manage all incoming chat messages in java socket programming

I am developing a program that has a chat feature and I am using sockets in it.
In my case, I want to handle each of the client in a different window chat(PLEASE SEE ATTACHED IMAGE).
As of now, when 1 client is connected, there is no problem. But when 2 clients are connected, the first client will be overridden by the 2nd one and he can't receive messages from server not unless I close the connection for the latest client connected(Server still receiving messages from all client although only 1 client can receive from server).
How am I gonna do this? I am using captain casa framework
I want to manage it like what did the image below do.
IMAGE HERE
Here is my code:
Server:
public void mainserver(){
Thread server = new Thread(new Runnable() {
#Override
public void run() {
try {
serverSocket = new ServerSocket(port);
System.out.println("Server Online... \nWaiting for Connections");
} catch (IOException e) {
e.printStackTrace();
}
while (accept){
try {
socket = serverSocket.accept();
System.out.println("New Connection Estasblished!!!");
chatHandler chat = new chatHandler(socket);
chat.start();
} catch (IOException e) {
System.out.println("server not terminate all connections");
System.exit(-1);
}
}
}
});
server.start();
}
public class chatHandler extends Thread{
Socket socket;
public chatHandler(Socket socket){
this.socket = socket;
}
public void run(){
try {
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF("Hi! Thank you for reaching us! How may I help you!?");
while (!read.equals(".end")){
read = din.readUTF();
if (getServerArea()!=null){
setServerArea(getServerArea()+"\n"+read);
}else {
setServerArea(read);
}
}
System.out.println("end of chat server");
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("Exit");
try {
dout.close();
din.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void serverSend(javax.faces.event.ActionEvent event) { // "Send" button
write = getServerField();
try {
dout.writeUTF(write);
dout.flush();
if (getServerArea()!=null){
setServerArea(getServerArea()+"\n"+write);
setServerField("");
}else {
setServerArea(write);
setServerField("");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(write);
}
Client:
public void client(){
Thread client = new Thread(new Runnable() {
#Override
public void run() {
try {
socket = new Socket("localhost",port);
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
while (!read.equals("bye")){
read = din.readUTF();
if (getClientArea()!=null){
setClientArea(getClientArea()+"\n"+read);
}else {
setClientArea(read);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
din.close();
dout.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
client.start();
}
public void clientSend(javax.faces.event.ActionEvent event) {
write = getClientField();
try {
dout.writeUTF(write);
dout.flush();
if (getClientArea()!=null){
setClientArea(getClientArea()+"\n"+write);
setClientField("");
}else {
setClientArea(write);
setClientField("");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(write);
}
I believe I understand the problem, and how to correct it.
You are using a unique thread (chatHandler) for each new connection.
This thread writes an automatic "Hello" upon connection, but thereafter is dedicated to reading messages (in the while loop you only read din) and updating the console accordingly. Since each thread is managing a reference to din, all incoming messages are OK.
However, it seems that writing back to a client (serverSend) is not in a thread; it is triggered by a button event. At this point, dout will be a reference to the most recent connection, and not a reference to the client intended to get the message. That is why the most recent client gets all future messages.
The correction is to choose the correct 'dout' for the intended client. When the server 'operator' chooses to write a message back (clicking the send button), somehow you need to obtain the correct 'dout' for that client.
One way to do this is to establish dout prior to creating the thread (using socket), and maintain a relationship between each client, and it's corresponding dout (i.e. in a Map).
If the problem is still not clear (that each client must have a unique reference to dout), please let me know and I will try to clarify.

ObjectInputStream is not able to recognize my Object Data format

I am getting EOFException from the following code:
if (!(in.read() == -1))
{
CANDataInfo canData = (CANDataInfo) in.readObject();
System.out.println(canData.toString());
bw.write(canData.toString());
}
else
{
System.out.println("in.read() == -1 "+in.readObject());
jLab0x28.setText("No more bytes to read ");
}
I am doing an Socket programming where server is sending continuos data to client at some interval. The Data whichis passed from server to client in via socket is of type CANDataInfo object which i have developed. At client side while i am printing the data i am getting exception. Since object's read is always -1 i am not able to log the data on some file.
Server Side Code:
private ServerSocket server = null;
private Socket client = null;
private ObjectOutputStream out;
public static final String TAG = "APP1";
private void structureData(CANDataInfo canDataInfo)
{
try
{
if(server == null)
{
server = new ServerSocket(38301);
server.setSoTimeout(0);
}
client = server.accept();
Log.e("Server ", ""+client.isConnected());
Log.e("Data ", ""+canDataInfo.toString());
if(!client.isConnected())
{
Log.e("Server ", "client.isConnected() "+client.isConnected());
server.close();
}
out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(canDataInfo);
out.close();
}
catch (Exception ex)
{
Log.e(CANManagerSetUp.TAG, "" + ex);
}
}
Client Side Code {Not a clean solution, Refer Answer from EJP}
package com.cnh.socket.client;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.swing.JLabel;
import cantest.setup.CANDataInfo;
public class ThreadListener
{
Socket client = null;
ObjectInputStream in = null;
ListenFor0X28 runnableListenFor0X28 = null;
boolean continueMe;
public class ListenFor0X28 implements Runnable
{
JLabel jLab0x28;
public ListenFor0X28(){}
public ListenFor0X28(boolean stop, JLabel jLab0x28)
{
continueMe = stop;
this.jLab0x28 = jLab0x28;
}
public void run()
{
while(continueMe)
{
try
{
client = new Socket("localhost", 38301);
in = new ObjectInputStream(client.getInputStream());
if(client.isConnected())
{
jLab0x28.setText("Connected to Server");
appendFile(continueMe, jLab0x28, client);
}
else
{
System.out.println("Client is trying to connect");
jLab0x28.setText("Client is trying to connect");
}
}
catch(Exception ex)
{
ex.printStackTrace();
System.err.println("Before Append "+ex.toString());
}
}
}
}
BufferedWriter file = getFile("C:\\ISSUE124_Resolved.txt");
private void appendFile(boolean continueMe, JLabel jLab0x28, Socket client)
{
try
{
if(!client.isClosed())
{
try
{
CANDataInfo canData = (CANDataInfo) in.readObject();
System.out.println(canData.toString());
file.write(canData.toString());
file.flush();
}
catch (EOFException exp)
{
continueMe = true;
System.out.println("A Stream has finished "+exp.toString()+"\n");
}
catch (ClassNotFoundException exp)
{
exp.printStackTrace();
System.err.println(exp.toString());
continueMe = false;
}
}
if(!continueMe)
{
file.close();
client.close();
in.close();
jLab0x28.setText("Socket is closed "+client.isClosed());
}
}
catch(IOException exp)
{
exp.printStackTrace();
System.err.println("Exception "+exp.toString());
jLab0x28.setText(exp.getMessage());
continueMe = false;
}
}
public BufferedWriter getFile(String path)
{
try
{
File file = new File(path);
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
return new BufferedWriter(fw);
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
Exception Stack: {Before Resolving}
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.cnh.socket.client.ThreadListener.appendFile(ThreadListener.java:73)
at com.cnh.socket.client.ThreadListener.access$0(ThreadListener.java:65)
at com.cnh.socket.client.ThreadListener$ListenFor0X28.run(ThreadListener.java:48)
at java.lang.Thread.run(Unknown Source)
Data received in unknown format java.io.EOFException
In the client
if (!(in.read() == -1))
{
CANDataInfo canData = (CANDataInfo) in.readObject();
System.out.println(canData.toString());
bw.write(canData.toString());
}
The first line reads one byte from the input stream. This is actually the first byte of the object that was written by the server. Thus the stream is no longer aligned correctly so the following readObject() fails.
You should remove the pointless and erroneous read() call, which is getting your object streams out of sync.
While you're at it, you can also remove all the redundant calls to isConnected(). They aren't doing anything. You seem to have a mania for calling extra methods which mostly don't do anything, or which try to predict the future. Try to taper off.
EDIT As requested I am critiquing not only your client but your server code.
Server:
private void structureData(CANDataInfo canDataInfo)
{
try
{
if(server == null)
The ServerSocket should have been created and configured in the constructor.
{
server = new ServerSocket(38301);
server.setSoTimeout(0);
Zero is the default. Don't assert defaults. Remove.
}
client = server.accept();
Log.e("Server ", ""+client.isConnected());
Logging isConnected() is redundant. Remove. This will always print true. The socket is connected. You just accepted it. If you want to log something useful, log the client socket's remote address.
Log.e("Data ", ""+canDataInfo.toString());
How can there be any data when you haven't read any yet? If this is invariant server-side data, why log it on every accept?
if(!client.isConnected())
{
Log.e("Server ", "client.isConnected() "+client.isConnected());
server.close();
}
This test can never pass, and the code block can never be entered, and if by some miracle it was entered, closing the server socket is a ridiculous response. Remove all this.
out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(canDataInfo);
out.close();
}
catch (Exception ex)
Don't catch Exception. Catch IOException.
{
Log.e(CANManagerSetUp.TAG, "" + ex);
You should log the exception class, its message, and the stack trace. ""+ex does not accomplish that.
}
}
Client:
public class ThreadListener
{
Socket client = null;
ObjectInputStream in = null;
ListenFor0X28 runnableListenFor0X28 = null;
boolean continueMe;
public class ListenFor0X28 implements Runnable
{
JLabel jLab0x28;
public ListenFor0X28(){}
public ListenFor0X28(boolean stop, JLabel jLab0x28)
{
continueMe = stop;
this.jLab0x28 = jLab0x28;
}
public void run()
{
while(continueMe)
{
try
{
client = new Socket("localhost", 38301);
in = new ObjectInputStream(client.getInputStream());
if(client.isConnected())
The client is connected. You just connected it, when you constructed the Socket. And if by some miracle it wasn't connected, calling getInputStream() would already have failed with a SocketException. Remove this test. In general there is far too much testing of things that can't be true or can't be false in your code.
{
jLab0x28.setText("Connected to Server");
appendFile(continueMe, jLab0x28, client);
}
else
{
System.out.println("Client is trying to connect");
jLab0x28.setText("Client is trying to connect");
}
}
The else block is unreachable, and the log message 'Client is trying to connect' is incorrect. Remove the entire block and the else.
catch(Exception ex)
See above. Don't catch Exception. Catch the exceptions the compiler tells you to catch: in this case IOException and the DNS-related ones.
{
ex.printStackTrace();
System.err.println("Before Append "+ex.toString());
See above about how to log exceptions.
}
}
}
}
BufferedWriter file = getFile("C:\\ISSUE124_Resolved.txt");
private void appendFile(boolean continueMe, JLabel jLab0x28, Socket client)
{
try
{
if(!client.isClosed())
{
try
{
CANDataInfo canData = (CANDataInfo) in.readObject();
System.out.println(canData.toString());
file.write(canData.toString());
file.flush();
}
catch (EOFException exp)
{
continueMe = true;
System.out.println("A Stream has finished "+exp.toString()+"\n");
}
catch (ClassNotFoundException exp)
{
exp.printStackTrace();
System.err.println(exp.toString());
continueMe = false;
}
}
if(!continueMe)
{
file.close();
client.close();
in.close();
You don't need to close both the input stream and the socket. Either will do. General practice is to close the outermost writer/output stream if there is one, otherwise the input stream.
jLab0x28.setText("Socket is closed "+client.isClosed());
}
}
catch(IOException exp)
{
exp.printStackTrace();
System.err.println("Exception "+exp.toString());
jLab0x28.setText(exp.getMessage());
continueMe = false;
}
}
public BufferedWriter getFile(String path)
{
try
{
File file = new File(path);
if (!file.exists())
{
file.createNewFile();
}
Here you are (1) testing for file existence and (2) creating a new file.
FileWriter fw = new FileWriter(file.getAbsoluteFile());
Here the operating system will create a new file regardless of what you did above. The exists()/createNewFile() part is therefore a complete waste of time: two system calls that accomplish precisely nothing. Remove them.
return new BufferedWriter(fw);
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
Poor practice. You should let this method throw IOException and not catch it internally, or return null. At present, if this method fails, you will get an instrutable NullPointerException when you go to use its return value.
}
}

Java can't get client or server response

I'm from Poland, so I'm sorry for any mistakes.
I've coding for a while a small server and client connection, when I stopped on annoying problem. When I send from client to server information (String), server can get it, but can't respone to it.
Here it is code.
Client
private static Socket socket;
public static void main(String args[]){
try{
String host = "localhost";
int port = 25002;
InetAddress address = InetAddress.getByName(host);
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 5000);
//Send the message to the server
System.out.println("< "+sendMessage(socket));
//socket.shutdownOutput();
System.out.println("> "+getMessage(socket));
}catch (SocketTimeoutException e){
System.out.println(e.getMessage()); // changed
}catch (IOException e){
System.out.println(e.getMessage()); // changed
}catch (IllegalBlockingModeException e){
System.out.println(e.getMessage()); // changed
}catch(IllegalArgumentException e){
System.out.println(e.getMessage()); // changed
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
System.out.println(e.getMessage()); // changed
}
}
}
public static String sendMessage(Socket client){
try {
String message = "test";
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer = new PrintWriter(client.getOutputStream(), true);
writer.print(message);
writer.flush();
writer.close();
return message;
} catch (IOException e) {
System.out.println(e.getMessage()); // changed
return "false";
}
}
public static String getMessage(Socket client){
try {
BufferedReader socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
return socketReader.readLine();
} catch (IOException e){
System.out.println(e.getMessage()); // changed
return "false";
}
}
And.. server
public class kRcon{
private static Socket socket;
private static ServerSocket serverSocket;
private static Thread u;
private static class Server extends Thread {
public void run() {
int port = 25002;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true) {
try {
socket = serverSocket.accept();
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String str = socketReader.readLine();
socketReader.close();
System.out.println(str);
socketWriter.write("test");
socketWriter.flush();
socketWriter.close();
}
}catch (IOException e1) {
e1.printStackTrace();
}
}
public static void init(){
try {
u = new Server();
u.setName("Server");
u.start();
} catch (IOException e) {
System.out.println(e.getMessage()); // changed
}
}
}
Results
If, I start server first all looks nice.
So, I start the client with parametr "test", nad output to console is:
< test
Socket is closed // changed
On server-side in console I have:
"test"
Socket is closed // changed
I tried to shutdown inputs and outputs and dosen't work.. I don't know to do now. Please help :c
Edited 2015-04-03
I've changed lines with comment "changed".
For Google, and readers
To fix problem, don't close StreamReaders nad StreamWriters on client's sides.
Thanks to EJP, for help!
Greetings from Poland.
When you get an exception, print it. Don't just throw away all that information. And don't return magic Strings either. In this case you should have let the exception propagate. If you had done all that you would have seen the exception SocketException: socket closed being thrown by getMessage(), and you would have had something concrete to investigate, instead of a complete mystery.
It is caused by closing the PrintWriter in sendMessage(). Closing either the input or output stream of a socket closes the other stream and the socket.

client/server connection closing causes loop error

I got to stage where client and server communicate, sending messages from and to each other.
The problem I am having is how to close the connection without causing an error?
If I terminate one of the apps (either server or client) that causes the connection to be lost, and then it causes the loop that is waiting for input to loop indefinitely and showing null's.
I tried closing sockets, buffers and even the thread, didn't work.
This is the client side
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
This is the server side
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(
socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Both use these classes:
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(
this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
//***HERE EXTRA BIT FOR THE SERVER
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(msg);
}
}
the only difference is the server has this bit where it says above ***HERE EXTRA BIT FOR THE SERVER
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Message recieved");
so basically, client connects, server accepts, then client sends message, servers receives message and shows it, and then sends "Message received" to the client, and the client shows it.
All this works fine, but once the connection is lost, they hang on showing null repeatedly, and I have to force the app to close.
You aren't checking for end of stream. If readLine() returns null, the peer has closed the connection, and you must do likewise and stop reading.
It's hard to believe you really need a new thread for every line to update the UI.

Categories