DataOutputStream works only preceded by System.out.println - java

I got another problem with input/output streams. Here i'm sending data from a server to a client. Before sending the data, the server send a little string just to say to the client what he'll send, and so the client know which function he should use to receive.
I'm receiving the first string well, but then i don't get the good integer and after that the second string i receive is "null".
Moreover, if i do a System.out.println before using the DataOutputStream with dos.writeInt, then everything works well.
I dont get it. here's the code:
Server:
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.SecureRandom;
public class Server {
private static OutputStream out;
static byte[] generateRandomBytes(int len) {
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[len];
random.nextBytes(bytes);
return bytes;
}
public static void sendType(String type) {
PrintWriter textWriter = new PrintWriter(out);
textWriter.println(type);
textWriter.flush();
}
public static void sendKeyNumber(int keyNumber) {
sendType("keyNumber");
try {
DataOutputStream dos = new DataOutputStream(out);
//System.out.println("Sending key number: " + keyNumber);
dos.writeInt(keyNumber);
//dos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void sendKey(byte[] key) {
sendType("key");
try {
DataOutputStream dos = new DataOutputStream(out);
//System.out.println("key length to send: " +key.length);
dos.writeInt(key.length); // write length of the byte array
//dos.flush();
dos.write(key);
//dos.flush();
System.out.println("key send: " +key);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket clientSocket ;
System.out.println("ouverture du server");
try {
ServerSocket serverSocket = new ServerSocket(2004);
clientSocket = serverSocket.accept();
out = clientSocket.getOutputStream();
sendKeyNumber(0);
byte[] keyBytes = generateRandomBytes(32);
sendKey(keyBytes);
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.crypto.spec.SecretKeySpec;
public class Main {
static InputStream in;
public static int receiveKeyNumber() {
DataInputStream dis = new DataInputStream(in);
int keyNumber = 0;
try {
keyNumber = dis.readInt();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return keyNumber;
}
public static SecretKeySpec receiveKey() {
DataInputStream dIn = new DataInputStream(in);
int length;
byte[] keyBytes = null;
try {
length = dIn.readInt(); // read length of incoming message
System.out.println("key length: " + length);
if(length!=32) {
System.err.println("Incorrect size for key: "+ length);
}
else {
keyBytes = new byte[length];
dIn.readFully(keyBytes, 0, keyBytes.length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec aesKey = new SecretKeySpec(keyBytes, "AES");
return aesKey;
}
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket(InetAddress.getLocalHost(),2004);
in = clientSocket.getInputStream();
while(!clientSocket.isClosed()) {
BufferedReader textReader = new BufferedReader(new InputStreamReader(in));
String type = textReader.readLine();
System.out.println(type);
if(type.equals("keyNumber")) {
int KN = receiveKeyNumber();
System.out.println(KN);
}
if(type.equals("key")) {
SecretKeySpec key = receiveKey();
System.out.println(key);
}
}
clientSocket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
End here's what i get (in Client console) when i don't do the System.out.println:
keyNumber
1801812234
null
I always get the same weird number; i've try to convert it to ASCII, but it's not readable.
Any suggestion?

In this case where binary data is sent, go entirely for DataOutputStream.
(Alternatively you could go for text.)
private static DataOutputStream out;
out = new DataOutputStream(clientSocket.getOutputStream());
public static void sendType(String type) {
out.writeUTF(type);
out.flush();
}
Flushing is important with binary conversations.
The problem with wrapping classes DataOutputStream, Printer, BufferedReader and such is that they start their own "cursor" and would close the wrapped I/O on their own closing. Having several DataOutputStreams is somewhat worrying; at least not as intended.
By the way my normal pattern is to do in main: new Server().exec(); or such.
That would remove all those statics.

Related

It duplicates content when transferring it via java socket

I have written a client-socket "system" that is supposed to upload a file.
Although, when I attempt to upload, content duplicates.
I'm pretty sure that it is because the program doesn't recognise the eof.
I've found something like "Object stream", but I don't fancy importing new classes. I reckon that I don't really require that. But I wanna know how what the problem precisely is and how to hanle it.
package client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
public static void main(String[] args) {
new Client();
}
public Client()
{
try {
socket = new Socket("127.0.0.1", 5010);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
this.sendFile("./some.txt");
in.close();
out.close();
socket.close();
}
catch(UnknownHostException ex)
{
System.out.println("unknown host");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendFile(String path)
{
int bytes = 0;
File file = new File(path);
FileInputStream input;
try {
input = new FileInputStream(file);
long size = file.length();
//long size = file.getTotalSpace();
System.out.println(size);
// send a file's size
out.writeLong(size);
byte[] buffer = new byte[1024];
int i = 0, r=0;
//while((bytes = input.read(buffer,0,buffer.length))!=-1)
while(size > 0 && (bytes = input.read(buffer,0,(int)Math.min(buffer.length, size)))!=-1)
{
System.out.println("\n -------------"+(++i));
for (byte b : buffer)
try
{
if ((char)b == '\n' || r == 0)
System.out.print("\n" + (++r));
System.out.print((char)b);
}
catch(NullPointerException ex)
{
}
out.write(buffer, 0, bytes);
out.flush();
size -= bytes;
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket ss;
private Socket cs;
private DataInputStream in;
private DataOutputStream out;
public static void main(String[] args) {
new Server();
}
public Server()
{
try {
ss = new ServerSocket(5010);
cs = ss.accept();
in = new DataInputStream(cs.getInputStream());
out = new DataOutputStream(cs.getOutputStream());
this.receiveFile("./uploaded.txt");
in.close();
out.close();
cs.close();
ss.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void receiveFile(String path)
{
int bytes = 0;
try {
File file = new File(path);
file.createNewFile();
FileOutputStream output = new FileOutputStream(file);
long size = in.readLong();
byte[] buffer = new byte[1024];
int i = 0;
while(size>0 && (bytes = in.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
System.out.println("\n -------------"+(++i));
for (byte b : buffer)
try
{
System.out.print((char)b);
}
catch(NullPointerException ex)
{
}
output.write(buffer, 0, bytes);
size -= bytes;
}
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem was that I didn't check if the size were 0 on the client side.
That try catch should NOT be in the for loop !!!! It only needs single code use by wrapping. Also use counting metering conventionally the number of bytes with a conventional numeric "for" loop, Not for(byte b : buffer). Note: byte is not strictly numeric, it will only reach to 255 in the for counter! It depends the quantity bytes required iterated over and should be as many as are packaged to it over the connection.
In the read you need to obtain the number of bytes sent andmark that into the write length to take from the array, so it would be better to instantiate the array based on the number of bytes or maximum bytes the the client sender has sent or negotiated as the maximum allowed (see the api docs for the stream.
NB ObjectStream does not apply , it's for RMI)
Of counting into the byte[] buffer array, you should remove it from the method and put it as a global. In the method , instantiate a new "buffer" array on the global variable each iteration of the loop according to the number of bytes read as it's new length.
The code does not appear to be particularly safe or debugable. You might try carefully constructing it starting again from scratch.

Java multi client chat server

I am new to Java programming and am trying to develop multi-client chat server.
following is my code:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
public class server implements Runnable{
private List<ServerClient> clients = new ArrayList<ServerClient>();
//private String UID;
private int port;
private ServerSocket socket;
private Thread run, manage, send, receive;
private boolean running = false;
public int i=0;
public server(int port){
// this.UID = UID;
this.port = port;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
run = new Thread(this, "Server");
run.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
running = true;
ManageClients();
receive();
}
private void ManageClients(){
manage = new Thread("Manage"){
public void run(){
while(running){
//managing
}
}
};
manage.start();
}
private void receive(){
receive = new Thread("Receive"){
public void run(){
Socket S1 = null;
try {
S1 = socket.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(running){
/* byte [] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String string = new String(packet.getData());
System.out.println(string);*/
/* BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String string = br.readLine();
System.out.println(string);
process(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
process(S1);
System.out.println(String.valueOf(i));
i++;
}
}
};
receive.start();
}
private void process(Socket S1){
BufferedReader br = null;
String string = "";
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
string = br.readLine();
System.out.println(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(string.startsWith("/c/")){
clients.add(new ServerClient("name", S1.getInetAddress(), S1.getPort(), "UID"));
}
else if(string.startsWith("/ip/")){
//send ip address to raspberry
System.out.println(string);
}
else if(string.startsWith("/r/")){
//send relay command to relay
System.out.println(string);
}
}
}
The server is accepting only one connection. If I try to connect another user the console does not show any output.
Can you please guide where I am going wrong.
Thank you
You need to run the accept method multiple times... once for each client that wants to connect. Typically people do that on a separate thread in a while loop since the accept method is blocking.
In your code it seems like you are only calling accept once, and hence you will only get one client connection.
I would recommend that you change your code architecture here, but if you want to keep it the same, and you know how many clients will connect, then you could wrap your access to socket in a synchronization lock, and call your receive method once for each client.

Connection reset at read()

I am trying to implement a server and client based on the web socket technologie but when I run the TCPDataServer class I am getting the following error:
java.io.IOException: connection reset
at java.io.DataInputStream.read(Unknown Source)
at org.server.ClientWorker.run(TCPDataServer.java:67)
at java.lang.Thread.run(Unknown Source)
I excepted to get the following output Hello, I am Alex!
TCPDataClient
package org.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPDataClient {
public static void main(String[] args) {
try {
TCPDataClient obj = new TCPDataClient();
Socket obj_client = new Socket(InetAddress.getByName("127.0.1"), 1000);
DataInputStream din = new DataInputStream(obj_client.getInputStream());
DataOutputStream dout = new DataOutputStream(obj_client.getOutputStream());
byte[] buffer = obj.createDataPacket("Hello, I am Alex!".getBytes("UTF8"));
dout.write(buffer);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private byte[] createDataPacket(byte[] data) {
byte[] packet = null;
try {
byte[] initialize = new byte[1];
initialize[0] = 2;
byte[] separator = new byte[1];
separator[0] = 4;
byte[] data_length = String.valueOf(data.length).getBytes("UIF8");
packet = new byte[initialize.length + separator.length + data_length.length + data.length];
System.arraycopy(initialize, 0, packet, 0, initialize.length);
System.arraycopy(data_length, 0, packet, initialize.length, data_length.length);
System.arraycopy(separator, 0, packet, initialize.length + data_length.length, separator.length);
System.arraycopy(data, 0, packet, initialize.length + data_length.length + separator.length, data.length);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return packet;
}
}
TCPDataServer
package org.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.logging.Level;
import com.sun.istack.internal.logging.Logger;
public class TCPDataServer {
public static void main(String[] args) {
try {
ServerSocket server_socket = new ServerSocket(1000);
while (true) {
new Thread(new ClientWorker(server_socket.accept())).start();
}
} catch (IOException e) {
System.err.println("Error");
System.err.println(e);
System.err.println("\n2");
System.err.println(e.getMessage());
System.err.println("\n3");
System.err.println(e.getLocalizedMessage());
System.err.println("\n4");
System.err.println(e.getCause());
System.err.println("\n5");
System.err.println(Arrays.toString(e.getStackTrace()));
System.err.println("\n6");
e.printStackTrace();
}
}
}
class ClientWorker implements Runnable {
private Socket target_socket;
private DataInputStream din;
private DataOutputStream dout;
public ClientWorker(Socket recv_scket) {
try {
target_socket = recv_scket;
din = new DataInputStream(target_socket.getInputStream());
dout = new DataOutputStream(target_socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] initilize = new byte[1];
try {
din.read(initilize, 0, initilize.length);
if (initilize[0] == 2) {
//This is line 67.
System.out.println(new String(readStream()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private byte[] readStream() {
byte[] data_buff = null;
try {
int b = 0;
String buff_length = "";
while ((b = din.read()) != 4) {
buff_length += (char) b;
}
int data_length = Integer.parseInt(buff_length);
data_buff = new byte[Integer.parseInt(buff_length)];
int byte_read = 0;
int byte_offset = 0;
while (byte_offset < data_length) {
byte_read = din.read(data_buff, byte_read, data_length - byte_offset);
byte_offset += byte_read;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data_buff;
}
}
In your Server program you have used din as your input stream reader which reads from the socket.
In your Client program you have used dout as output stream writer which writes to the underlying socket
In your ClientWorker class you have given multiple read operations using dinfrom the socket, whereas you have given only one write operation to the stream using dout object.
The din object will be blocking/waiting to receive the data from client side, but unfortunately you would have closed (program ends) your socket connection on your client which is reason for the DataInputStream to throw IOException.
And your din object will throw an IO error if your underlying socket/stream has been close and yet you are trying read using it.
Try to maintain the same number of reads and writes on either side (client/server).
You aren't closing the sockets, so your OS is resetting them when the JVM exits.

Java socket server not responding

I am getting started with java sockets just out of inquisitiveness.
I wrote a small piece of code, a server and a client.
The server accepts a string and converts it to upper case and returns to the client.
I want the server to be able to handle multiple clients and have a persistent connection.
Here is the server code :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
private ServerSocket listener;
private ArrayList<Socket> clients;
public Server() throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(7575);
}
public Server(int port) throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(port);
}
public void start() throws IOException, InterruptedException{
Thread one = new Thread(){
public void run(){
while (true){
Socket socket = null;
try {
socket = listener.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (socket.isConnected()){
try {
socket.setKeepAlive(true);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clients.add(socket);
System.out.println(socket.getRemoteSocketAddress().toString());
}
}
}
};
Thread two = new Thread(){
public void run(){
try {
while (true){
work();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
one.start();
two.start();
one.join();
two.join();
stop();
}
private void stop() throws IOException{
listener.close();
}
private void work() throws IOException{
if (clients.size() == 0){
return;
}
for(int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (!socket.isClosed()){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String data = br.readLine();
if (data == null) continue;
out.println(data.toUpperCase());
}
else{
clients.remove(socket);
}
}
}
}
package entry;
import java.io.IOException;
import server.Server;
public class Main {
public static void main(String args[]) throws IOException{
Server server = new Server();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is the client :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[])throws IOException{
Socket socket = new Socket("192.168.0.110", 7575);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream(), true);
while (true){
System.out.println("\n\nEnter a string : ");
String inp = br.readLine();
if (inp.equals("quit")) break;
pr.println(inp);
System.out.println("The response is : " + sr.readLine());
}
socket.close();
}
}
Strange thing here is when I set a breakpoint in the server code and step through the code in eclipse, the code is working exactly as expected i.e I am getting the response in the client.
But when I run it directly in eclipse, I am not getting the response in the client.
Cannot understand what is going wrong.
Edit
I seem to have fixed the issue.
Here is the code snippet :
Thread two = new Thread(){
public void run(){
try {
while (true){
Thread.sleep(1000); //This is the added line
work();
}
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
But I am still confused about what made the timing difference.
Is there any cleaner way to achieve this ?
I've solved the problem with a different approach.
Here is the new Approach:
ServerHandler.java :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerHandler extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private ArrayList<Socket> clients;
public ServerHandler(Socket socket) throws IOException{
this.socket = socket;
clients = new ArrayList<Socket>();
if (!clients.contains(socket)){
clients.add(this.socket);
System.out.println(this.socket.getRemoteSocketAddress());
}
}
#Override
public void run(){
while (true){
if (clients.isEmpty()) break;
String str = null;
for (int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (socket.isClosed()){
clients.remove(socket);
continue;
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
str = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(str.toUpperCase());
}
}
}
}
Main.java [for running the server] :
package entry;
import java.io.IOException;
import java.net.ServerSocket;
import server.ServerHandler;
public class Main {
public static void main(String args[]) throws IOException{
ServerSocket listener = new ServerSocket(7575);
try{
while (true){
new ServerHandler(listener.accept()).start();
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
listener.close();
}
}
}
Ok, Here we go.I don't understand the use of Arraylist for maintaining Connections unless You are handling the messy details for each Client.
The most used or prefered approach for handling multiple clients at a time can be understood in terms of an example:
Server.java
import java.net.ServerSocket;
import java.io.IOException;
class Server {
public static void main(String[] args) throws IOException {
try( ServerSocket ss = new ServerSocket(3333)) { // try with resources
new ServerThread(ss.accept()).start();
}
}
}
As you can see, I just defined a Class that will listen for Client connections, and as soon a request is made to the server it will start a Thread which is defined in the next class. A point to be noted here is the use of Try-with-Resources block. Any class that implements the Closeable interface can be enclosed within this try statement. The try-with-resources automatically handles closing of streams or connections for me. This means, you remove all your redundant try-catch blocks from your code and use this try instead.
Now,
ServerThread.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket s = null;
public ServerThread(Socket s) {
super("ServerThread");
this.s = s;
}
public void run() {
try( PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("In Server");
String in, out;
while ((in = stream.readLine()) != null) {
System.out.println("Msg 4m client: " + in);
if(in.equals("bye"))
break;
out = write.readLine();
pw.println(out);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Observe the try-with-resources statement over here, We can initialize multiple Connections/Input-Output Streams here, All of the opened connection will automatically be closed as soon as the compiler returns from try statement.Also, Observe the while statement, it will keep on running until the client is sending messages, and will quit if the message is "bye".
Finally, a Client program that sends request to the server.
Client.java
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Client {
public static void main(String[] args) {
try( Socket s = new Socket("localhost", 3333);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in)) ) {
System.out.println("In Client");
String in;
while ((in = write.readLine()) != null) {
pw.println(in);
if(in.equals("bye"))
break;
System.out.println("Msg 4m server: " + stream.readLine());
}
} catch(IOException e) {
System.err.println("Exception: " + e);
}
}
}
Notice, the while Statement here, it will loop until the user is entering messages, and if the message is "bye", it will quit.Rest of the program can be easily understood from above explanation.

Client - Server : How to Let Server send the received message to another client instead of sending it back to original client?

I am trying to code a chat in my java software,
i have 2 eclipses running on my windows 7.
one of the eclipses includes a project "ServerListener" which contains a class Server.java
and the other eclipse includes a project "Client" and contains a class cl.java.
I am sending messages from my cl.java to the server.java
each time the server receives a message he send it back to the cl.java (the one i sent the message from) to make sure it's connected.
(THIS PART WORKS FINE sending message to the server and back from the server to the same client)
my question is :
how to let the server.java send the message to another client instead of the original client?
if i run another eclipse with the same project as "Client"
i want to the two eclipses to chat together
this is the Server.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();
public static void main(String[] args) {
new Server();
}
public Server() {
// ServerSocket is only opened once !!!
try {
serverSocket = new ServerSocket(6000);
System.out.println("Waiting on port 6000...");
boolean connected = true;
// this method will block until a client will call me
while (connected) {
Socket singleClient = serverSocket.accept();
// add to the list
ServerThread myThread = new ServerThread(singleClient);
allClients.add(myThread);
myThread.start();
}
// here we also close the main server socket
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServerThread extends Thread {
Socket threadSocket;
String msg;
boolean isClientConnected;
InputStream input;
ObjectInputStream ois;
OutputStream output;
ObjectOutputStream oos; // ObjectOutputStream
public ServerThread(Socket s) {
threadSocket = s;
}
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
input = threadSocket.getInputStream();
ois = new ObjectInputStream(input);
output = threadSocket.getOutputStream();
oos = new ObjectOutputStream(output);
// get the user name from the client and store
// it inside thread class for later use
//msg = (String) ois.readObject();
isClientConnected = true;
//System.out.println(msg);
for(ServerThread t:allClients)
t.sendText("User has connected...");
// send this information to all users
// dos.writeUTF(userName + " has connected..");
// for(ServerThread t:allClients)
// t.sendText(msg);
while (isClientConnected) {
System.out.println("connect ... ");
try {
msg = (String) ois.readObject();
System.out.println(msg);
if (msg.equals("quit"))
break;
for (ServerThread t : allClients)
t.sendText(msg);
} catch (Exception e) {
}
}
// close all resources (streams and sockets)
ois.close();
oos.close();
threadSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
this is the client (cl.java):
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;
static ConnectThread clientThread;
boolean isConnected;
static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
public static void main(String[] args) {
new cl();
}
public cl() {
connectUser();
}
public void connectUser() {
clientThread = new ConnectThread();
clientThread.start();
}
class ConnectThread extends Thread {
InputStream input;
OutputStream output;
ObjectOutputStream oos;
Socket s;
public void sendText(String text) {
try {
System.out.println("sending text to server..");
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
s = new Socket(HOST, PORT);
output = s.getOutputStream();
oos = new ObjectOutputStream(output);
isOnline = true;
isConnected = true;
new ListenThread(s).start();
while (isOnline) {
System.out.println("Enter a Text to send:");
msg = scanner.nextLine();
clientThread.sendText("amjad: " + msg);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ListenThread extends Thread {
Socket s;
InputStream input;
ObjectInputStream ois;
public ListenThread(Socket s) {
this.s = s;
try {
input = s.getInputStream();
ois = new ObjectInputStream(input);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while (isConnected) {
try {
final String inputMessage = (String) ois.readObject();
System.out.println(inputMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
thanks in advance

Categories

Resources