image of a error:image
i am creating a multi threaded client server chat with 2 clients. The program gives no errors, but the message I send does not reach the client, how can I do it? writing
hello # client 1
the message should get to the second client but it doesn't.
how do i change the client name?
Below I leave the files respectively of the server and the client that I wrote:
import java.io.*;
import java.util.*;
import java.net.*;
public class Server{
static Vector<ClientHandler> lc = new Vector<>();
static int i = 0;
public static void main(String[] args) throws UnknownHostException, IOException{
ServerSocket ss = new ServerSocket(2104);
while (true){
Socket s = ss.accept();
System.out.println("Ricevuta nuova richiesta del client " + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
ClientHandler ch = new ClientHandler(s,"Client numero" + i, dis, dos);
Thread t = new Thread(ch);
System.out.println("Il client si sta aggiungendo alla lista");
lc.add(ch);
t.start();
i++;
}
}
}
class ClientHandler implements Runnable{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean login;
public ClientHandler(Socket s, String name, DataInputStream dis, DataOutputStream dos){
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.login=true;
}
#Override
public void run(){
String ricevuta;
while (true){
try{
ricevuta = dis.readUTF();
System.out.println(ricevuta);
if(ricevuta.equals("logout")){
this.login=false;
this.s.close();
break;
}
StringTokenizer st = new StringTokenizer(ricevuta, "#");
String MsgToSend = st.nextToken();
String recipient = st.nextToken();
for (ClientHandler mc : Server.lc){
if (mc.name.equals(recipient) && mc.login==true){
mc.dos.writeUTF(this.name+ " : " +MsgToSend);
break;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
try{
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
final static int ServerPort = 2104;
public static void main(String args[]) throws UnknownHostException, IOException{
Scanner scn = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("localhost");
Socket s = new Socket(ip, ServerPort);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread sendMessage = new Thread(new Runnable(){
#Override
public void run(){
while (true){
String messaggio = scn.nextLine();
try {
dos.writeUTF(messaggio);
} catch (IOException e){
e.printStackTrace();
}
}
}
});
Thread readMessage = new Thread(new Runnable(){
#Override
public void run(){
while (true){
try {
String messaggio = dis.readUTF();
System.out.println(messaggio);
} catch (IOException e){
e.printStackTrace();
}
}
}
});
sendMessage.start();
readMessage.start();
}
}
Related
I am creating a simple Java program where the client sends a message to the server and the server replies back with a confirmation message. But my question is: Can I get the server response/broadcast before the BufferedReader line?
Server:
public class Multithread extends Thread{
Socket sock;
static ArrayList<Multithread> clientList = new ArrayList<Multithread>();
public Multithread(Socket sock){
this.sock = sock;
}
public void run(){
try{
DataInputStream in = new DataInputStream(this.sock.getInputStream());
String read = in.readUTF();
if(read.equalsIgnoreCase("exit")){
System.out.println(this.sock.getRemoteSocketAddress()+" just dced");
clientList.remove(this);
this.sock.close();
}
else{
String said = this.sock.getRemoteSocketAddress() +" said "+read;
System.out.println(said);
for(Multithread multi : clientList){
DataOutputStream o = new DataOutputStream(multi.sock.getOutputStream());
o.writeUTF(said);
}
this.sock.close();}
}catch(IOException e){
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(7777);
System.out.println("Listening");
while(true){
Socket socket = serverSocket.accept();
System.out.println("Connected to "+socket.getRemoteSocketAddress());
Multithread multi = new Multithread(socket);
clientList.add(multi);
multi.start();
}
}
}
Client:
public class Clients{
public static void main(String[] args) throws UnknownHostException, IOException {
while(true){
Socket socket = new Socket("localhost",7777);
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
out.writeUTF(line);
if(line.equalsIgnoreCase("exit"))
{
System.out.println("Disconnected");
socket.close();
break;
}
else{
System.out.println("Server said :"+in.readUTF());
socket.close();
}
}
}
}
I'm trying to code an instant messaging system... Initially, I'm doing it this way, and once I get it to work I'll add the GUI.
Once a client sends a message to the server, the server is supposed to display it to all the other clients. How can I do that? I've been trying a few things but it keeps displaying only to the client that sent the message...
Thanks in advance!
SERVER
import java.io.*;
import java.net.*;
class Server {
//one per server
static int port = 3000;
private int backlog = 100;
ServerSocket main;
static DataOutputStream dataOut;
static DataInputStream dataIn;
static String scannerMessage;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static class MailServer extends Thread {
//one per client
static int index;
String name = Client.name;
public MailServer(int index, DataInputStream in, DataOutputStream out) {
Server.dataIn = in;
Server.dataOut = out;
this.index = index; // thread index, one per client
}
public void run() {
while (true) {
try {
String receivedMessage = dataIn.readUTF();
//print receivedMessage to all clients
} catch (Exception e) {
break;
}
}
}
}
public Server(int port) throws Exception {
this.main = new ServerSocket(port);
}
// start a serve
public void serve() throws Exception {
int index = 1;
while (true) {
Socket socket = this.main.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream dataIn = new DataInputStream(in);
DataOutputStream dataOut = new DataOutputStream(out);
// handle the connection
// keep reading using an infintite loop
System.out.println("Handling connection to Client " + index + "...");
(new MailServer(index, dataIn, dataOut)).start();
index += 1; // add one every time a new client is added
}
}
public static void main(String[] args) throws Exception {
Server s = new Server(port);
System.out.println("Serving....");
s.serve();
}
}
CLIENT
import java.io.*;
import java.net.*;
class Client {
static String hostname = "127.0.0.1";
static int port = Server.port;
static Socket socket;
static String name;
static class Sender extends Thread {
DataOutputStream dataOut;
public Sender(DataOutputStream dataOut) {
this.dataOut = dataOut;
}
public void run() {
while(true) {
//get a message from the user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String message = br.readLine();
dataOut.writeUTF(message);
dataOut.flush();
} catch(Exception e) {
break;
}
}
}
}
static class Receiver extends Thread {
DataInputStream dataIn;
public Receiver(DataInputStream dataIn) {
this.dataIn = dataIn;
}
public void run() {
while(true) {
try {
//RECEIVE A MESAGE FROM THE SERVER (ending in \n)
String msg = dataIn.readUTF();
while (msg != null) {
System.out.println(msg);
msg = dataIn.readUTF();
}
} catch(Exception e) {
break;
}
}
}
}
//client will require host name and the port
public Client(String hostname, int port) throws Exception {
socket = new Socket(hostname, port);
}
public void connect() throws Exception {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream dataIn = new DataInputStream(in);
DataOutputStream dataOut = new DataOutputStream(out);
//handle the connection
System.out.println("Handling connection to server...");
Thread sender = new Sender(dataOut);
Thread receiver = new Receiver(dataIn);
sender.start();
receiver.start();
sender.join();
receiver.join();
System.out.println("Client " + Server.MailServer.index);
System.out.println("----------------------");
}
public static void main(String[] args) throws Exception {
Client c = new Client(hostname, port);
c.connect();
}
}
Update: I created a list of all the MailServer objects and then iterated through them to send the message to all the clients, as JP Moresmau suggested... but now the first Client to send something receives all the outputs. Why is this? How can I fix it... ? Thank you, and sorry if my questions seem too obvious or dumb, I'm still a Java noob:(
SERVER - UPDATED
package csci2020_assignment51;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Server {
//one per server
static int port = 3000;
private int backlog = 100;
ServerSocket main;
static DataOutputStream dataOut;
static DataInputStream dataIn;
static String scannerMessage;
static List<MailServer> mailServers = Collections.<MailServer>synchronizedList(new ArrayList<MailServer>());
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static class MailServer extends Thread {
//one per client
static int index;
String name = Client.name;
public MailServer(int index, DataInputStream in, DataOutputStream out) {
Server.dataIn = in;
Server.dataOut = out;
this.index = index; // thread index, one per client
}
public void run() {
while (true) {
try {
String receivedMessage = dataIn.readUTF();
String outputMessage = "Client " + index + " said: " + receivedMessage;
//print receivedMessage to all clients
for (MailServer mailserver : mailServers) {
dataOut.writeUTF(outputMessage);
}
} catch (Exception e) {
break;
}
}
}
}
public Server(int port) throws Exception {
this.main = new ServerSocket(port);
}
// start a serve
public void serve() throws Exception {
int index = 1;
while (true) {
Socket socket = this.main.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream dataIn = new DataInputStream(in);
DataOutputStream dataOut = new DataOutputStream(out);
// handle the connection
// keep reading using an infintite loop
System.out.println("Handling connection to Client " + index + "...");
MailServer mailServer = new MailServer(index, dataIn, dataOut);
mailServer.start();
mailServers.add(mailServer);
dataOut.writeUTF("Client " + index);
index += 1; // add one every time a new client is added
}
}
public static void main(String[] args) throws Exception {
Server s = new Server(port);
System.out.println("Serving....");
s.serve();
}
}
Have a static list of all the MailServer objects you create
static List<MailServer> servers=Collections.<MailServer>synchronizedList(new LinkedList<MailServer>);
...
MailServer s=new MailServer(index, dataIn, dataOut);
servers.add(s);
s.start();
Then loop through them all when one of them receives a message, and for all expect the receiver, write the message to their output.
The big problem in your code is that dataOut and dataIn are unique! You need to move them to the MailServer class. Each MailServer talks to one specific client and hence needs to have their own streams.
static class MailServer extends Thread {
DataOutputStream dataOut;
DataInputStream dataIn;
And your notification loop becomes:
for(MailServer mailServer:mailServers){
if (mailServer!=this){
mailServer.dataOut.writeUtf(...);
}
}
I also don't understand how you expect to get the Client.name in the server, since Client runs on another machine... Get rid of that for now.
Multiple Clients say(A, B, C, D etc) make connection to one server through same socket. They all send messages to server as and when required. Client messages are sent only to server(and not to other clients). But whenever server sends a message it should be delivered to all the clients. Please help me out jam only able to get server message on only 1 client
//MultithreadedServer.java
package server;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Vector;
public class MultithreadedServer
{
Vector<ClientHandler> clients = new Vector<ClientHandler>();
Vector<String> users = new Vector<String>();
private static ServerSocket servSocket;
private static final int PORT = 1247;
public MultithreadedServer() throws IOException{
servSocket = new ServerSocket(PORT);
while(true) {
Socket client = servSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler handler;
handler = new ClientHandler(client);
clients.add(handler);
}
}
public static void main(String[] args) throws IOException
{
MultithreadedServer ms = new MultithreadedServer();
}
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
String name,message,response;
public ClientHandler(Socket socket)
{
//Set up reference to associated socket...
client = socket;
try
{
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(
client.getOutputStream(),true);
}
catch(IOException e)
{
e.printStackTrace();
}
start();
}
public void sendMessage(String msg) {
System.out.println("is it even coming here?");
out.println("Server:" + msg);
}
public void boradcast(String message) {
// send message to all connected users
for (ClientHandler c : clients) {
c.out.println("Server: hello");
}
}
public String getUserName() {
return name;
}
public void run()
{
try
{
String received;
do
{ System.out.println("Enter Your Message: ");
String msg = in.readLine();
out.println(msg);
boradcast("testing");
received = in.readLine();
out.println("ECHO: " + received);
//Repeat above until 'QUIT' sent by client...
}while (!received.equals("QUIT"));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (client!=null)
{
System.out.println(
"Closing down connection...");
client.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}}
//ClientProgram
import java.io.*;
import java.net.*;
public class Client
{
private static InetAddress host;
private static final int PORT = 1247;
private static Socket link;
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader keyboard;
public static void main(String[] args) throws IOException
{
try
{
host = InetAddress.getLocalHost();
link = new Socket(host, PORT);
in = new BufferedReader(
new InputStreamReader(
link.getInputStream()));
out = new PrintWriter(
link.getOutputStream(),true);
keyboard = new BufferedReader(
new InputStreamReader(System.in));
String message, response;
do
{
System.out.print(
"Enter message ('QUIT' to exit): ");
message = keyboard.readLine();
//Send message to server on
//the socket's output stream...
out.println(message);
//Accept response frm server on
//the socket's input stream...
response = in.readLine();
//Display server's response to user...
System.out.println(response);
}while (!message.equals("QUIT"));
}
catch(UnknownHostException uhEx)
{
System.out.println(
"\nHost ID not found!\n");
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
if (link!=null)
{
System.out.println(
"Closing down connection...");
link.close();
}
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
}
}
}
An obvious way to do this would be to cycle through all ClientHandlers in clients and send the message to each of them:
for (ClientHandler ch : clients){
ch.sendMessage(message); //Or something
}
A single client connects to a single server.
I'm unable to display the text sent from the client.
Am I not sending the text properly from client or not receiving the text properly on Server?
Is there another way to check from the code? (on client side that the data has been sent) or (on server side that the data has been received)
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class ChatServer {
public static void main(String[] args) throws IOException {
ChatServer chatServer = new ChatServer();
chatServer.go();
}
private void go() throws IOException {
//Generate a random number and write to a text file
Random randomGenerator = new Random();
int randomInt = 1024 + randomGenerator.nextInt(64511);
PrintWriter printWriter = new PrintWriter("port.txt");
printWriter.write(String.valueOf(randomInt));
printWriter.flush();
//Create Server on a port using that random number
ServerSocket serverSocket = new ServerSocket(randomInt);
System.out.println("Server on Port: "+randomInt);
//Start Accepting Clients
ClientHandler clientHandler= new ClientHandler(serverSocket);
Thread t = new Thread(clientHandler);
t.start();
}
private class ClientHandler implements Runnable {
ServerSocket serverSocket;
BufferedReader bufferedReader;
PrintWriter writer;
Socket socket;
public ClientHandler(ServerSocket sSocket) throws IOException {
serverSocket = sSocket;
}
public void run() {
while (true)
{
String message;
try {
//Accept A connection and assign a socket for this client
socket = serverSocket.accept();
System.out.println("Connection Established");
//Read Message
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
while( (message = bufferedReader.readLine()) != null)
{
//Display it on the console
System.out.println("From Client: " + message);
//Send it back to the client
writer = new PrintWriter(socket.getOutputStream());
writer.println("Your message is: " + message);
writer.flush();
//Send your message
writer.write("This is default message");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is Client Side Code
package com.company;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
Socket socket;
public static void main(String[] args) throws IOException {
ChatClient chatClient = new ChatClient();
chatClient.go();
}
private void go() throws IOException {
//Read Port number from file
FileReader fileReader = new FileReader("port.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int port = Integer.parseInt(bufferedReader.readLine());
//Connect to socket on the port number
System.out.println("Connecting to Server on: "+port);
socket = new Socket("127.0.0.1",port);
//Initiate sender thread
ChatSender chatSender = new ChatSender(socket);
Thread sender = new Thread(chatSender);
//Initiate receiver thread
ChatReceiver chatReceiver = new ChatReceiver(socket);
Thread receiver = new Thread(chatReceiver);
sender.start();
receiver.start();
}
public class ChatSender implements Runnable
{
BufferedWriter bufferedWriter;
public ChatSender(Socket socket) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
bufferedWriter = new BufferedWriter(outputStreamWriter);
}
public void run()
{
while (true)
{
//get text from console
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("To Server: "+input);
try {
System.out.println("Sending data");
//write to server
bufferedWriter.write(input);
//flush the text
bufferedWriter.flush();
System.out.println("sent data");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ChatReceiver implements Runnable
{
BufferedReader bufferedReader;
public ChatReceiver(Socket socket) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
}
public void run()
{
try {
while (true)
{
Thread.sleep(1000);
System.out.println("Receiving data");
String output = bufferedReader.readLine();
System.out.print("From Server: "+output);
System.out.println("Received data");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Usual problem. You're reading lines, but you aren't sending lines. Change write() to println().
I develop code to send form client to server then the server has to send what it receives from client again to client. but in my code the server only receives the message but does not resend it again. I do not know what is the problem
This is my client code
public class Client implements Runnable{
private static Socket s = null;
//private static BufferedOutputStream fromUser = null;
private static DataInputStream fromServer = null;
private static InputStreamReader input = new InputStreamReader(System.in);
private static InputStreamReader inputstreamreader = null;
private static BufferedReader bufferedreader = null;
private static DataOutputStream fromUser = null;
private static int chara = 0;
private static String line = null;
static int port = 0;
static String host = null;
//connect to server
#Override
public void run() {
try {
inputstreamreader = new InputStreamReader(s.getInputStream());
bufferedreader = new BufferedReader(inputstreamreader);
//charr = fromClient.read();
while(true){
if ((line = bufferedreader.readLine()) != null){
System.out.println(line);}
if(line.equals(-1)){
break;
}
}//end while
}catch(NullPointerException e) {
// do something other
}
catch (IOException e) {
System.out.println(e);
}
}//end the run
//constructor with two arguments
public Client(String host, int port){
try{
s = new Socket (host,port);
}
catch(Exception e){}
}
//send message to from Client to Server
public static void sendToServer(){
try{
fromUser =new DataOutputStream (new BufferedOutputStream(s.getOutputStream()));
chara =input.read();
while(true){
if (chara == '~'){
break;}
fromUser.write(chara);
fromUser.flush();
chara =input.read();
}//end while
}
catch (IOException e) {
System.out.println(e);
}
}//end send message
I tried to use thread to receive message but also does not work. I tried without thread it does not work too.
public static void main(String [] args){
host = args[0];
port = Integer.parseInt(args[1]);
System.out.println("Start connection .....");
Client client = new Client(host,port);
Thread thread = new Thread(client);
thread.start();
//connect(host,port);
client.sendToServer();
client.close();
}//end main
and this is my server code
public class Server extends Thread{
private static Socket s = null;
private static ServerSocket ss = null;
private static DataOutputStream fromUser = null;
private static DataInputStream fromClient = null;
private static InputStreamReader input = new InputStreamReader(System.in);
private static InputStreamReader inputstreamreader = null;
private static BufferedReader bufferedreader = null;
static String line=null;
static String sendC;
private static int chara = 0;
static int port = 0;
//connect to server
static void connect(int port){
try{
ss = new ServerSocket (port);
System.out.println("Listening on port "+port+"...");
s = ss.accept();
System.out.println("Has been connected .....");
}
catch (IOException e) {
System.out.println(e);
}
}//end of the connection method
//send message to from Client to Server
public static void sendToClient(String text){
try{
fromUser =new DataOutputStream (new BufferedOutputStream(s.getOutputStream()));
sendC =text;
fromUser.write(sendC.getBytes());
fromUser.flush();
}
catch (IOException e) {
System.out.println(e);
}
}//end send message
public static void receiveFromClient(){
try {
inputstreamreader = new InputStreamReader(s.getInputStream());
bufferedreader = new BufferedReader(inputstreamreader);
//charr = fromClient.read();
while(true){
if ((line = bufferedreader.readLine()) != null){
System.out.println(line);
sendToClient(line);}
if(line.equals(-1)){
break;
}
}//end while
}catch(NullPointerException e) {
// do something other
}
catch (IOException e) {
System.out.println(e);
}
}//end send message
this is main method for server
public static void main(String [] args){
port = Integer.parseInt(args[0]);
System.out.println("Start connection .....");
connect(port);
receiveFromClient();
//sendToClient();
close();
}//end main
I do not have alot of knowledge in java especially about the socket
thanks for your help
a simply search for a java echo server shows this
public class EchoServer {
public static void main(String[] args) throws Exception {
// create socket
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
In in = new In (clientSocket);
Out out = new Out(clientSocket);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
out.close();
in.close();
clientSocket.close();
}
}
}
see http://introcs.cs.princeton.edu/java/84network/EchoServer.java.html