I'm doing a school project where we are supposed to create a simplefied Hotel booking system and then use it with a server/client communication.
Since I wanted to push the project a bit and do a multithreaded program, I've got a Socket Exception that I'm not sure how to handle. I've searched everywhere for an answer and I know that the exception occours because I'm trying to use a socket that has been closed. But from what I've read on Oracle-docs, their example is doing that as well.
So, is this actually Ok, just that I need to handle the exception? Cause my code runs fine, I just see the exceptions since I've put e.printStackTrace(); in my catch.
My Client class:
package client;
import java.io.*;
import java.net.Socket;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
Socket client = new Socket("localhost", 6066);
//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);
LocalDate localDate = LocalDate.now();
String date = DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate);
System.out.println(in.readUTF());
System.out.print("Namn: ");
String name = sc.nextLine();
System.out.print("Ålder: ");
String age = sc.nextLine();
out.writeUTF(name);
out.writeUTF(age);
out.writeUTF(date);
System.out.println(in.readUTF());
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
And my Server class:
package server;
import java.io.IOException;
import java.net.*;
public class Server {
public static void main(String [] args) throws IOException {
int port = 6066;
ServerSocket server = new ServerSocket(port);
while(true) {
System.out.println("Listening for client..");
try {
Socket connectedClient = server.accept();
ClientHandle ch = new ClientHandle(connectedClient);
Thread t = new Thread((Runnable) ch);
t.start();
}catch (IOException e) {
}
}
}
}
And then my ClientHandle class which has the run() for the server-side:
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.*;
import resources.*;
public class ClientHandle implements Runnable{
Socket connectedClient;
DataInputStream in;
DataOutputStream out;
public ClientHandle(Socket connectedClient) {
this.connectedClient = connectedClient;
try{
this.in = new DataInputStream(this.connectedClient.getInputStream());
this.out = new DataOutputStream(this.connectedClient.getOutputStream());
}catch(IOException ex) {
}
}
Hotel hotel = new Hotel();
Ticket yourTicket = new Ticket();
Server server = new Server();
#Override
public void run() {
while (true) {
try {
InetAddress host = InetAddress.getLocalHost();
System.out.println("Client " + host + " has connected.");
out.writeUTF("Välkommen till Hotel Gisslevik!\nVänligen fyll i nedan information för att slutföra din bokning.\n");
String yourName = in.readUTF();
String age = in.readUTF();
int yourAge = Integer.parseInt(age);
String date = in.readUTF();
yourTicket.setDate(date);
Person guest = new Person(yourName, yourAge);
hotel.setRooms();
Integer room = hotel.getRoom();
String rent = "J";
if (rent.indexOf("J") >= 0) {
yourTicket.setId(yourName);
if (hotel.checkIn(guest, room, yourTicket.getId(), yourTicket.getDate())) {
String yourId = yourTicket.getId();
out.writeUTF("\nDitt rum är nu bokat den " + date + ". \nBokningsnummer: " + yourId);
}
}
out.flush();
connectedClient.close();
}catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
If I just comment e.printStackTrace(); the exceptions doesn't show, but I would like to know how to handle them (if they should be handled). I've been searching the internet for days and checked out tutorials, but I don't find a proper answer to this.
I really appreciate any help you can provide.
Handle java.net.SocketException: Socket closed
Don't close the socket and then continue to use it.
when multithreading?
Irrelevant.
You have connectedClient.close() inside your while (true) loop. Solution: move it outside.
Related
This is my 2nd ever Post I'm pretty new to Programming.
I'm working on making my Socket Server Concurrent (Multithreaded) on the Server side. I understand I have to use Threaded Pools after my Socket accepts but I'm just very confused what to do. currently the requests are slower then it was when it was only iterative because its not working correctly.
//MultiClient Class
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.net.*;
import java.io.*;
public class MultiServer {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
System.out.println("What port should the server be using?");
int portNumber = scnr.nextInt();
while ((portNumber < 1025) ||(portNumber > 4998)) {
System.out.println("Please enter a Port Number between '1025' and '4998'.");
portNumber = scnr.nextInt();
}
try (ServerSocket serverSock = new ServerSocket(portNumber)){
System.out.println("Server listening on port " + portNumber);
while(true) {
Socket sock = serverSock.accept();
MultiServerHandler msh = new MultiServerHandler(sock);
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
executor.execute(msh);
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
//MultiClientHandler Class
import java.io.*;
import java.net.*;
public class MultiServerHandler extends Thread{
private Socket sock;
public MultiServerHandler(Socket sock) {
this.sock = sock;
}
public void run() {
try {
System.out.println("New client connected");
InputStream input = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = sock.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
String command;
command = reader.readLine();
Process process = Runtime.getRuntime().exec(command);
BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
String result;
while((result = read.readLine()) != null) {
writer.println(result);
}
sock.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
So far I just know I have to implement it after the socket accepts but I'm not too sure yet.
I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.
I am unable to figure out how to stop the message from appearing twice on both the client's screen.
The Actual output should be something like this:
Steps for Running the code:
1. Run Server on one terminal
2. Run two clients on two different terminals
When I run the Server - main method creates a Server object:
public static void main(String[] args) throws IOException {
Server server = new Server();
}
Server Constructor:
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
I am using Socket to connect to the server. Here is my Server code.
Server.java
import java.io.IOException;
import java.net.*;
import java.util.Vector;
import java.io.*;
import java.util.*;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.*;
import java.util.Scanner;
public class Server {
static Vector<Socket> ClientSockets;
int clientCount = 0;
//int i = 0;
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
public static void main(String[] args) throws IOException {
Server server = new Server();
}
class AcceptClient extends Thread {
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
AcceptClient(Socket client) throws IOException {
ClientSocket = client;
din = new DataInputStream(ClientSocket.getInputStream());
dout = new DataOutputStream(ClientSocket.getOutputStream());
//String LoginName = din.readUTF();
//i = clientCount;
clientCount++;
ClientSockets.add(ClientSocket);
//System.out.println(ClientSockets.elementAt(i));
//System.out.println(ClientSockets.elementAt(1));
start();
}
public void run() {
try {
while (true) {
String msgFromClient = din.readUTF();
System.out.println(msgFromClient);
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(msgFromClient);
pOut.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Client.java
import java.net.Socket;
import java.util.Scanner;
import java.io.*;
import java.net.*;
public class Client implements Runnable{
Socket socketConnection;
DataOutputStream outToServer;
DataInputStream din;
Client() throws UnknownHostException, IOException {
socketConnection = new Socket("127.0.0.1", 8000);
outToServer = new DataOutputStream(socketConnection.getOutputStream());
din = new DataInputStream(socketConnection.getInputStream());
Thread thread;
thread = new Thread(this);
thread.start();
BufferedReader br = null;
String ClientName = null;
Scanner input = new Scanner(System.in);
String SQL = "";
try {
System.out.print("Enter you name: ");
ClientName = input.next();
ClientName += ": ";
//QUERY PASSING
br = new BufferedReader(new InputStreamReader(System.in));
while (!SQL.equalsIgnoreCase("exit")) {
System.out.println();
System.out.print(ClientName);
SQL = br.readLine();
//SQL = input.next();
outToServer.writeUTF(ClientName + SQL);
//outToServer.flush();
//System.out.println(din.readUTF());
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] arg) throws UnknownHostException, IOException {
Client client = new Client();
}
public void run() {
while (true) {
try {
System.out.println("\n" + din.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The reason you have this is because you're sending the server whatever the client has written in the console, and the server sends it back to all of the clients (including the sender).
So you're writing a message in the console (and you see it) and then you're receiving it back as one of the clients (and you see it again).
A simple fix would be not to send the just received message back to the client (he already sees it in the console). Add this to the Server.AcceptClient#run method:
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
if(ClientSocket.equals(pSocket)){
continue;
}
...
I have a server that accepts sockets from whenever a client connects. I want to be able to shutdown my local server and let my client try to reconnect for about 5 times, and if I start my server the client should indicate that you have reconnected again.
I understand somewhat that this is done in the try{} catch(IOException){Here goes the code for handleing reconnect} I want to use the same socket that I first used to connect. I don't want to create a new Client cause then I have to enter username and stuff like that all over again
I tried to creating a new socket like clientSocket = new Socket("localhost", portnr) but I don't know if this is the correct way to go. If you have examples that answers this please link them. I dont mind reading as long as it is good documented. Thanks in advance!
EDIT.
Here is my Client Class
public class Client {
public static void main(String[] args) {
Client client = new Client();
client.connect();
}
//------------------------------------------------------------
//METHOD CONNECT
//------------------------------------------------------------
private void connect(){
int reConnectTries = 0;
Socket clientsocket;
try {
//------------------------------------------------
//Sets up variables needded for execution
clientsocket = new Socket("localhost", 8900);
DataOutputStream OUT = new DataOutputStream(clientsocket.getOutputStream());
ListenforMessages listen = new ListenforMessages(clientsocket);
//We don't want to enter username all the time
//So this goes not in the while-loop
//------------------------------------------------
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter username");
String username = keyboard.nextLine();
//Sends username to sever so it can be added to a list
OUT.writeUTF(username);
//------------------------------------------------
//------------------------------
//Creates a thread to listen on messages from server(Other clients in this case)
Thread trd = new Thread(listen);
trd.start();
//------------------------------
while (true) {
try {
String sendMessage = keyboard.nextLine();
OUT.writeUTF(sendMessage);
OUT.flush();
} catch (Exception e) {
System.err.println("Could not send message to server. " + e);
}
}
} catch (IOException e) {
System.err.println("Couldnt establish a connection: " + e);
}
}
//------------------------------------------------------------
//CLASS FOR HANDLEING INPUT. We create a class for input on a new thread
//This is cause we don't want it to block other processes.
//----------------------------------------------------------------
class ListenforMessages implements Runnable{
Socket mySocket;
DataInputStream IN;
public ListenforMessages(Socket X) throws IOException {
this.mySocket = X;
}
#Override
public void run() {
try {
IN = new DataInputStream(mySocket.getInputStream());
while (true) {
System.out.println(IN.readUTF());
}
} catch (Exception e) {
System.err.println("Couldn't fetch message from server.Error: " + e);
}
}
}
}
There's a couple of solutions to this problem, but a simple one would to be have the client try to reconnect (open a new connection to the server) at set intervals. For example, you could try something like this to have your client try to reconnect once every 3 minutes:
while(true) {
try {
clientSocket = new Socket("localhost", portnr);
break; // We connected! Exit the loop.
} catch(IOException e) {
// Reconnect failed, wait.
try {
TimeUnit.MINUTES.sleep(3);
} catch(InterruptedException ie) {
// Interrupted.
}
}
}
This way, the client will try to connect, and if it fails, wait for 3 minutes before trying again.
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.NoRouteToHostException;
import java.net.SocketAddress;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
final class TCPClient{
private static Scanner in ;
private static DataOutputStream douts;
private static OutputStream outs;
private static InputStream ins;
private static DataInputStream dins;
private static String ip;
private static Integer port;
private int count = 0;
private static int times;
public TCPClient(){
serverConTest(port);
}
private boolean portIsOpenOrNot(String ip, int port){
try{
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip,port),500);
socket.close();
return true;
}catch(Exception e){
}
return false;
}
private void serverConTest(int port){
while(true){
try{
InetAddress addr = InetAddress.getByName(ip);
SocketAddress sockaddr = new InetSocketAddress(addr,port);
Socket socket = new Socket();
System.out.println("Connecting To server...");
socket.connect(sockaddr);
Thread.sleep(1000);
boolean isactive = true;
if(portIsOpenOrNot(ip,port)){
outs = socket.getOutputStream();
douts = new DataOutputStream(outs);
System.out.println("Sending Request to server:");
while(isactive){
Thread.sleep(1000);
douts.writeUTF("Are you Alive..!");
ins = socket.getInputStream();
dins = new DataInputStream(ins);
System.out.println("Response from server : "+dins.readUTF());
}
}
}catch(SocketException e){
System.out.println("Connection lost");
}catch(IOException e){
break;
}catch(InterruptedException e){
System.out.print("connection timeout in 50 second.");
break;
}
}
}
public static void main(String[] args){
in = new Scanner(System.in);
System.out.print("Enter ip : ");
ip = in.nextLine();
System.out.print("Enter Port : ");
port = Integer.parseInt(in.next());
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(new Runnable() {
public void run() {
new TCPClient();
}
});
try{
future.get(50, TimeUnit.SECONDS);
}catch(InterruptedException e){
}catch(ExecutionException e){
}catch(TimeoutException e){
executorService.shutdownNow();
}
}
}
This sample will give you the complete understanding that when the server restarts then client will reconnects.
I didnt read all your code but this one is working for me
And dont forget to add the Server class and the method send that sends messages...
Client :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
static Socket sock=null;
static DataInputStream in=null;
static DataOutputStream out=null;
static boolean connected=false;
static String currentip="";
static int currentport=0;
static void refreching(){
try {
in=new DataInputStream(sock.getInputStream());
out=new DataOutputStream(sock.getOutputStream());
Thread gg=new Thread() {
String msg="";
public void run() {
while(connected) {
try {
msg=in.readUTF();
System.out.println(msg);
} catch (IOException e) {
connected=false;
System.out.println("Reconnecing...");
while(!connected)
connect(currentip,currentport);
}
}
}
};
gg.start();
}
catch(Exception e) {
System.out.println("Problem while reading incoming and outgoing"+
"messages!");
connected=false;
}
}
static void connect(String iphost, int port){
try{
sock=new Socket(iphost,port);
currentip=iphost;
currentport=port;
connected=true;
refreching();
System.out.println("Connected!");
}
catch(Exception e){
System.out.println("Cant connect !");
connected=false;
}
}
public static void main(String[] args) {
connect("127.0.0.1",1234); //Example you can enter another's computer ip
//adress if connected to the same network !!!
//Send(Message_To_Server); Dont forget to add the sending code!!!
//Maybe i'll upload a video one day==>how to create a chat application
}
Here's my code:
SERVER:
package server;
public class Main {
public static void main(String args[]) {
new EchoServer(9000);
}
}
+
package server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private ServerSocket server;
public EchoServer(int port) {
try {
server = new ServerSocket(port);
while (true) {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(in.readLine() + " | MOD");
socket.close();
}
} catch(Exception err) {
err.printStackTrace();
}
}
}
CLIENT:
package client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[]) {
try {
while (true) {
Socket socket = new Socket("localhost", 9000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
out.println(input.readLine());
System.out.println(in.readLine());
socket.close();
}
} catch (Exception err) {
System.out.println(err);
}
}
}
It works all as it should, except that I want when the server sends the "message" + " | MOD" to the client, I want the server to send that to all clients, how can I do that?
I am new to Java, but not to coding so please help me if I've done some wrong stuff that can be done easier or better.
Please help.
Thanks alot.
What you can do is save the client sockets in an array, and then use a for loop to send to each socket.
First, declare your clientSocket array; note that 5 is just an arbitrary size used for testing. Also, declare a counter int.
public Socket clientSocket[] = new Socket[5];
public int intLastSocket = 0;
// this should be placed where you're waiting to accept connections
while (true) {
printTCP("Ready to accept welcome socket");
clientSocket[intLastSocket] = welcomeSocket.accept();
intLastSocket++;
}
// on the server, call this to send. s is a reference to the server object
public void sendToAllTCP(TCPServer s, String message) {
for (Socket z : s.clientSocket) {
if (z != null) {
PrintStream outToClient = null;
try {
outToClient = new PrintStream(z.getOutputStream());
outToClient.println(message);
} catch (IOException e) {
TCPServer.printTCP("Caught an IO exception trying "
+ "to send to TCP connections");
e.printStackTrace();
}
}
}
}
IN YOUR CODE:
package com.murplyx.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private ServerSocket server;
// use the clientSocket Array to save each new connection
public Socket clientSocket[] = new Socket[5];
public EchoServer(int port) {
try {
server = new ServerSocket(port);
// this should be placed where you're waiting to accept connections
while (true) {
System.out.println("Ready to accept welcome socket");
clientSocket[intLastSocket] = server.accept();
intLastSocket++;
//send your message here, note that putting
//it here will send it each time u add a new connection
sendToAllTCP(/*the message you want to send */);
}
} catch(Exception err) {
err.printStackTrace();
}
}
public void sendToAllTCP(String message) {
// this is an enchanced for loop, i don't know if it's in other languages
// but in java it's supposed to let you loop through
//each object in any iterable list
// such as array, arraylist, linkedlist, etc
for (Socket z : clientSocket) {
if (z != null) {
//basically this chunk of code declares output and input streams
//for each socket in your array of saved sockets
PrintStream outToClient = null;
try {
outToClient = new PrintStream(z.getOutputStream());
outToClient.println(message);
} catch (IOException e) {
System.out.println("Caught an IO exception trying "
+ "to send to TCP connections");
e.printStackTrace();
}
}
}
}
}
Depending on when you want to send your message, you can use the console and sys.in to send it. For example, if you read a line from sys.in and it .equals("sendMsg"), then you can call sendToAllTCP(yourmessage)
You should take a look at multiThreaded chat Server. Each client wich connects gets it's own thread.
Here is the perfect answer to your question:
multithread client-server chat, using sockets
Good luck mate!