Java server client networking - java

Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ?
Im sending data using BufferedWriter but this methid just seems to work for one time only, after doing the write and the flush method Im able just to send 1 message to my server, then it just doesnt get the data im sending...
Client connects - sends data to server (1st time) - Works
Client sends data again - no data echoed on server console.
Should I open a bufferedwriter each time I want to send data or keep one open all the time and never close it?
My actual code - Client side
Main
public class Main {
public static void main(String args[]) {
Client chat = new Client("localhost", 6111);
}
}
Client
public class Client {
public Client(String host, int port) {
SwingUtilities.invokeLater(new Runnable() {
private Socket chat;
public void run() {
try {
this.chat = new Socket("localhost", 6113);
} catch ( IOException e) {
e.printStackTrace();
}
Gui gui = new Gui("Chat", this.chat);
}
});
}
}
GUI
public class Gui {
private JFrame frame;
private JTextArea area;
private JTextField field;
private JMenuBar menu;
private JButton button;
private Socket socket;
private BufferedWriter write;
public Gui(String title, Socket socket) {
this.socket = socket;
try {
this.write = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
this.frame = new JFrame(title);
this.frame.setSize(new Dimension(400, 400));
this.frame.setLayout(new BorderLayout());
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setResizable(false);
Elements interfce = new Elements(this.frame);
this.field = interfce.addField("Texto to send...");
this.menu = interfce.addBar();
this.area = interfce.addArea();
this.button = interfce.addButton("Send");
this.button.addActionListener(new Listener(this.field, this.socket, this.write));
this.menu.add(this.field);
this.menu.add(this.button);
this.frame.setVisible(true);
}
}
Listener (sends data)
public class Listener implements ActionListener {
private JTextField text;
private Socket chat;
private BufferedWriter writer;
public Listener(JTextField field, Socket chat, BufferedWriter write) {
this.text = field;
this.chat = chat;
this.writer = write;
}
public void actionPerformed(ActionEvent e) {
System.out.println(this.text.getText());
try {
writer.write("Hello\n");
writer.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
And the server
public class Main {
public static void main(String args[]) {
Server chat = new Server(6113);
}
}
public class Server {
private int port;
private ServerSocket server;
public Server(int port) {
this.port = port;
startServer();
}
public void startServer() {
try {
this.server = new ServerSocket(this.port);
System.out.println("Starting chat server at port " + this.port + "...");
while (true) {
Socket s = this.server.accept();
System.out.println("Client connected - " + s.getLocalAddress().getHostName());
Thread client = new Thread(new Client(s));
client.start();
}
} catch (IOException e) {
System.out.println("Error found!");
e.printStackTrace();
}
}
}
public class Client implements Runnable {
private Socket client;
public Client(Socket client) {
this.client = client;
}
public void run() {
try {
BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
System.out.println("Client says - " + read.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}

Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ?
Connection between a Client and Server is generally open for the entire session of messaging and not recreated for sending each message. So keep it open until the client or the Server has to go away.
Look at your Client thread that you start in your server upon accepting a Connection.
public void run() {
try {
BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
System.out.println("Client says - " + read.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
Does this give you a hint ? Well - you have to arrange for some sort of looping here within your run() - listening for more inputs from that client.

Just do some changes
Server side:
public void run() {
try {
BufferedReader read = new BufferedReader(new InputStreamReader(
this.client.getInputStream()));
while (true) {
System.out.println("Client says - " + read.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client side:
use PrintWriter instead of BufferedWriter that provide print new line functionality and auto flush property.
this.write = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()),
true);
....
public void actionPerformed(ActionEvent e) {
System.out.println(this.text.getText());
try {
writer.write(this.text.getText());
writer.println();
} catch (Exception e1) {
e1.printStackTrace();
}
}

Related

I can not connect to my server via another computer

I am writing a program to eventually make my own file server. I am having issues with connecting to the server in a web browser via typing myIpAddress:port into the browser while the server is running. This does work if I use one computer to both host the server and be a client, but does not if I use a second computer to be a client.
I have 2 classes, Index and ClientHandler
public class Index {
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(8080);
DevInterface myFace = new DevInterface(server);
System.out.println("Listening for connection on port 8080");
} catch (IOException e) {
e.printStackTrace();
}
int i = 0;
while(true) {
Socket client = null;
try {
client = server.accept();
ClientHandler clientHandler = new ClientHandler(client);
clientHandler.start();
System.out.println("got a client");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
and my ClientHandler class which is what sends my html to the server is this.
public class ClientHandler extends Thread{
private Socket client = null;
private PrintWriter out = null;
ArrayList<Socket> clientList = null;
public ClientHandler(Socket client) {
this.client = client;
}
public ClientHandler(Socket client, ArrayList<Socket> clientList) {
this.client = client;
this.clientList = clientList;
}
public void run() {
try {
out = new PrintWriter(client.getOutputStream());
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("\r\n");
out.println("<p>Hello World</p>");
out.flush();
out.close();
if(client!=null) {client.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Java Sockets - How can I send messages to multiple threads?

I made a Chat Application (Server/Client) using Java. Note: The server is ran as its own jar file and each client is ran as its own jar file.
Each client is on their own thread.
Whenever I send messages to the server, each client receives the message, however when I send messages from the client, only the server receives the message. When the client sends a message, I want all connected clients and the server to receive the message so all of the clients can communicate together and with the server as well.
I've looked at multiple posts and videos about this, but most were too confusing for me to understand.
Could someone please help me understand how I can send messages between threads? Thanks!
-- My Code --
Client:
public Client(User user, String address, int port) {
try {
socket = new Socket(address, port);
ClientApplicationUI app = new ClientApplicationUI();
app.setTitle("Chat Application - " + user.getUsername());
app.setVisible(true);
ServerConnection connection = new ServerConnection(socket, app);
output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
new Thread(connection).start();
app.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (app.getTextField().getText() != null && app.getTextField().getText().length() > 0) {
String message = MessageUtil.getMessage(Message.LOGGER_PREFIX) + " <" + user.getUsername() + "> " + app.getTextField().getText() + "\n";
try {
output.writeUTF(message);
output.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
} catch (UnknownHostException e) {
System.out.println(e);
System.out.println("Could not connect! Reason: " + e);
} catch (IOException e) {
System.out.println("Could not connect! Reason: " + e);
}
}
ServerConnection
public class ServerConnection implements Runnable {
#SuppressWarnings("unused")
private Socket socket;
private DataInputStream in;
private ClientApplicationUI app;
public ServerConnection(Socket socket, ClientApplicationUI app) throws IOException {
this.socket = socket;
this.app = app;
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
#Override
public void run() {
while (true) {
String message;
try {
message = in.readUTF();
app.logMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server
public class Server {
private Socket socket = null;
private ServerSocket server = null;
private ExecutorService pool = Executors.newFixedThreadPool(4);
public Server (int port) {
try {
ApplicationUI app = new ApplicationUI();
app.setVisible(true);
server = new ServerSocket(port);
app.logMessage(MessageUtil.getMessage(Message.LOGGER_PREFIX) + " " + MessageUtil.getMessage(Message.INFO) + " Server started!\n");
app.logMessage(MessageUtil.getMessage(Message.LOGGER_PREFIX) + " " + MessageUtil.getMessage(Message.INFO) + " Waiting for new connections...\n");
while (true) {
socket = server.accept();
ConnectionHandler clientThread = new ConnectionHandler(socket, app);
app.logMessage(MessageUtil.getMessage(Message.LOGGER_PREFIX) + " " + MessageUtil.getMessage(Message.INFO) + " A new client has been accepted!\n");
pool.execute(clientThread);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server(58139);
}
}
ConnectionHandler
public class ConnectionHandler implements Runnable {
private Socket client;
private ApplicationUI app;
private DataInputStream in;
private DataOutputStream out;
public ConnectionHandler(Socket client, ApplicationUI app) throws IOException {
this.client = client;
this.app = app;
in = new DataInputStream(new BufferedInputStream(client.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
}
#Override
public void run() {
try {
app.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (app.getTextField().getText() != null && app.getTextField().getText().length() > 0) {
String message = MessageUtil.getMessage(Message.LOGGER_PREFIX) + " <Server> " + app.getTextField().getText() + "\n";
try {
sendMessage(message);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
String message = "";
while (!message.equals("/stop")) {
message = in.readUTF();
app.logMessage(message);
}
} catch (IOException e) {
System.err.println("IO exception in connection handler!");
System.err.println(e.getStackTrace());
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendMessage(String message) throws IOException {
out.writeUTF(message);
out.flush();
}
}
You need to understand, how sockets work. They are always Client and Server.
There are two ways you could achieve what you want:
First solution:
Send the message which is meant for all clients to the server and let the server distribute the message to all the other clients. The server will need to keep track of the already connected clients, i.e. store their Socket.
Second solution: (which totally is not advisable)
If you want to send a message to a client of a network without haveing the actual server involved, you will need that client to act as a server, or the other way around. This means that every client will actually need to listen to every other client, instead of only the server.
You should definitely go with the first solution!

Java chat application only picking up some sent messages

I'm writing an all-in-one java chat program which will either act as a client or a server. I'm currently having this problem where, after the connection is established, the program only successfully recieves (or sends?) some of the messages. I've used a loop to spam through a load of junk and I've seen that the other end will only pick up some of the messages. I've never got a message to send manually.
Here is the code:
public class ConnectionThread implements Runnable {
private Connection c = Connection.getInstance();
private ChatInterface chatInterface;
private static ConnectionThread serverThread;
private ServerSocket serverSocket;
private Socket socket;
private ObjectInputStream dataIn;
private ObjectOutputStream dataOut;
public ConnectionThread() {}
public static synchronized ConnectionThread getInstance() {
if (serverThread == null) {
serverThread = new ConnectionThread();
}
return serverThread;
}
public void run() {
// If the programs role is server, set up the server
if (c.getRole() == ConnectionRole.SERVER) {
try {
setupServer();
waitForConnection();
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
chatInterface.addToChatHistory(dataIn.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
} while (c.getRole() == ConnectionRole.SERVER);
}
// If the programs role is client, set up a connection to the server
if (c.getRole() == ConnectionRole.CLIENT) {
try {
setupClient();
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
chatInterface.addToChatHistory(dataIn.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
} while (c.getRole() == ConnectionRole.CLIENT);
}
}
private void setupClient() throws IOException {
System.out.println("ATTEMPTING TO CONNECT...");
socket = new Socket("127.0.0.1", 8080);
System.out.println("CONNECTED!");
}
private void setupServer() throws IOException {
System.out.println("SETTING UP SERVER..");
serverSocket = new ServerSocket(8080, 1);
System.out.println("SERVER SETUP");
}
private void waitForConnection() throws IOException {
System.out.println("WAITING FOR A CONNECTION...");
socket = serverSocket.accept();
System.out.println("CONNECTION RECIEVED");
}
private void setupStreams() throws IOException {
System.out.println("SETTING UP STREAMS...");
dataOut = new ObjectOutputStream(socket.getOutputStream());
dataIn = new ObjectInputStream(socket.getInputStream());
chatInterface = ChatInterface.getInstance();
System.out.println("STREAMS SETUP");
}
public void sendMessage(String message) throws IOException {
System.out.println("SENDING MESSAGE...");
dataOut.writeUTF(message);
chatInterface.addToChatHistory(message);
System.out.println("MESSAGE SENT!");
}
}
Can anyone tell me why not all messages are being sent/picked up properly? I've been playing with it for quite a while now and I can't figure out why.
I found out after following EJP's recommendation to switch to DataInput/OutputStreams which worked straight away. Although I did need to be using ObjectInput/OutputStreams so I switched back. I found that I got the same issue again, until I switched to write/readObject instead of write/readUTF. If I cast the readObject to (String) it would then manage to receive every message.
So if anyone is having the same problem with ObjectInput/OutputStreams using write/readUTF try using write/readObject instead.

How to write A ServerSocket which accept multiple clicent Socket?

I am working on Socket programming. I have build such a server which should accept multiple Clients. Here I have particular num of clients , clients keeps on sending msg to Server every 10sec , Server has to process it.The problem I am having is I am unable to connect multiple Server and here a single client is a continuous running programm in while(true) So if one client Sends a request another client can not connect . Here is my Program.
Server
public class SimpleServer extends Thread {
private ServerSocket serverSocket = null;
private Socket s1 = null;
SimpleServer() {
try {
serverSocket = new ServerSocket(1231);
this.start();
} catch (IOException ex) {
System.out.println("Exception on new ServerSocket: " + ex);
}
}
public void run() {
while (true) {
try {
System.out.println("Waiting for connect to client");
s1 = serverSocket.accept();
System.out.println("Connection received from " + s1.getInetAddress().getHostName());
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = dis.readUTF();
System.out.println(st);
s1In.close();
dis.close();
s1.close();
// throw new ArithmeticException();
} catch (IOException ex) {
Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception e) {
System.out.println("Exceptiopn: "+e);
}
}
}
public static void main(String args[]) throws IOException {
new SimpleServer();
}
}
Server is working fine but I am not able to write Client program which shoud run in while(true) loop for sending msg to Server and allow other client also connect to Server.
but for a single client I write like this ,
public class SimClient extends Thread {
private Socket s1 = null;
SimClient() {
//this.start();
}
public void run() {
int i=0;
try {
s1 = new Socket("localhost", 1231);
} catch (IOException ex) {
Logger.getLogger(SimClient.class.getName()).log(Level.SEVERE, null, ex);
}
// while (i<10) {
try {
// Open your connection to a server, at port dfg1231
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Data from Client:");
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
s1out.close();
dos.close();
// s1.close();
i++;
} catch (IOException ex) {
//ex.printStackTrace();
System.out.println("Exception in While: "+ex.getMessage());
}
//}
}
public static void main(String args[]) throws IOException {
SimClient s= new SimClient();
s.start();
}
}
So can any one help me to write client program. its a great help for me.
just as you have a Thread for the ServerSocket, you need to create a Thread for every Socket returned by serverSocket.accept() , then it loops back around immediately to block and wait to accept another Socket. Make a class called SocketHander which extends Thread and accepts a Socket in the constructor.
public class SocketHandler extends Thread {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket = socket;
}
public void run() {
// use the socket here
}
}
and back in the ServerSocket handler...
for (;;) {
SocketHandler socketHander = new SocketHandler(serverSocket.accept());
socketHander.start();
}
It is generally a good idea to use a Fixed Size Thread Pool because creating Threads in a ad-hoc manner may cause the Server to run out of Threads if the requests are high.
public class SimpleServer extends Thread {
private ServerSocket serverSocket = null;
private static ExecutorService executor = Executors.newFixedThreadPool(100);
SimpleServer() {
try {
serverSocket = new ServerSocket(1231);
this.start();
} catch (IOException ex) {
System.out.println("Exception on new ServerSocket: " + ex);
}
}
public void run() {
while (true) {
try {
System.out.println("Waiting for connect to client");
final Socket s1 = serverSocket.accept();
executor.execute(new Runnable() {
public void run() {
try {
System.out.println("Connection received from " + s1.getInetAddress().getHostName());
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = dis.readUTF();
System.out.println(st);
s1In.close();
dis.close();
s1.close();
} catch(Exception e) {
System.out.println("Exceptiopn: "+e);
}
// throw new ArithmeticException();
}});
} catch (IOException ex) {
Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
System.out.println("Exceptiopn: "+e);
}
}
}
public static void main(String args[]) throws IOException {
new SimpleServer();
}
}

Listening on multiple sockets (InputStreamReader)

I'm having a problem with a little game I'm designing in my class.
The problem is that I got two clients connected to a server. (client1 and client2) They are each running a game, which in the end, closes the window. As the game window is a JDialog, it will then, when it's closed, send a message, through a socket, to the server, telling it that it's done. I want the server to know which of the two clients were completed first. They are reporting through a PrintWriter on the sockets' OutputStream.
What I did was this:
in1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
in2 = new BufferedReader(new InputStreamReader(client2.getInputStream()));
try {
in1.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in2.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
Problem is that it waits for the first input, before it even starts listening on the second. How can I make it listen on both at the same time? Or solve my problem some other way.
Thanks!
Server connection should work like this:
Server gameServer = new Server();
ServerSocket server;
try {
server = new ServerSocket(10100);
// .. server setting should be done here
} catch (IOException e) {
System.out.println("Could not start server!");
return ;
}
while (true) {
Socket client = null;
try {
client = server.accept();
gameServer.handleConnection(client);
} catch (IOException e) {
e.printStackTrace();
}
}
In hanleConnection() you start a new thread and run the communication for this client in the created thread. Then the server can accept a new connection (in the old thread).
public class Server {
private ExecutorService executor = Executors.newCachedThreadPool();
public void handleConnection(Socket client) throws IOException {
PlayerConnection newPlayer = new PlayerConnection(this, client);
this.executor.execute(newPlayer);
}
// add methods to handle requests from PlayerConnection
}
The PlayerConnection class:
public class PlayerConnection implements Runnable {
private Server parent;
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
protected PlayerConnection(Server parent, Socket socket) throws IOException {
try {
socket.setSoTimeout(0);
socket.setKeepAlive(true);
} catch (SocketException e) {}
this.parent = parent;
this.socket = socket;
this.out = new DataOutputStream(socket.getOutputStream());;
this.in = new DataInputStream(socket.getInputStream());
}
#Override
public void run() {
while(!this.socket.isClosed()) {
try {
int nextEvent = this.in.readInt();
switch (nextEvent) {
// handle event and inform Server
}
} catch (IOException e) {}
}
try {
this.closeConnection();
} catch (IOException e) {}
}
}

Categories

Resources