Many clients using different computers java chatbox - java

I am making a simple java chatbox using sockets. When I run many clients on same computer, everything's alright, but when I try it on different PCs, they don't share the information. How could I fix that? I guess that has something to do with port and host, not sure though. My connecting method is below.
public static void Connect() {
try {
final int port = 444;
String hostname = "";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
final String host = "Laurie-PC";
Socket sock = new Socket(host, port);
System.out.println("You connected to " + host);
ChatClient = new A_Chat_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(UserName);
out.flush();
Thread X = new Thread(ChatClient);
X.start();
} catch (Exception E) {
System.out.println(E);
JOptionPane.showMessageDialog(null, "Server not responding");
System.exit(0);
}
}

this is the server code
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class A_Chat_Server {
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
try {
final int port = 444;
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for clients...");
A_Chat_Client_GUI.main(args);
while (true) {
Socket sock = server.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
AddUserName(sock);
A_Chat_Server_Return chat = new A_Chat_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch (Exception X) {
System.out.println(X);
}
}
public static void AddUserName(Socket X) throws IOException {
Scanner input = new Scanner(X.getInputStream());
String UserName = input.nextLine();
CurrentUsers.add(UserName);
for (int i = 0; i < A_Chat_Server.ConnectionArray.size(); i++) {
Socket temp_sock = A_Chat_Server.ConnectionArray.get(i);
PrintWriter out = new PrintWriter(temp_sock.getOutputStream());
out.println("????1!!!!!!???#######22" + CurrentUsers);
out.flush();
}
}
}

Related

Socket Programming Implementation Using Threading in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Here I can solve socket programming for chat application between multiple client and server where client can send multiple message to the server. But now I want to solve a new problem where conversion of any string from any client [each client can send at most 2 messages] into a FULL UPPERCASE string with the help of the server. The server will be able to serve at most 5 clients.
This is my client coe.....
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("Client started..");
Socket socket = new Socket("127.0.0.1", 22222);
System.out.println("Client Connected..");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
if(message.equals("exit")){
break;
}
//sent to server...
oos.writeObject(message);
try {
//receive from server..
Object fromServer = ois.readObject();
System.out.println("From Server: " + (String) fromServer);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
socket.close();
}
}
This is my server code........
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(22222);
System.out.println("Server Started..");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected..");
// new Server Thread Start.....
new ServerThread(socket);
}
}
}
class ServerThread implements Runnable {
Socket clientSocket;
Thread t;
ServerThread(Socket clientSocket) {
this.clientSocket = clientSocket;
t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
//read from client...
Object cMsg = ois.readObject();
if (cMsg == null)
break;
System.out.println("From Client: " + (String) cMsg);
String serverMsg = (String) cMsg;
serverMsg = serverMsg.toUpperCase();
//send to client..
oos.writeObject(serverMsg);
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Sever side
package sockettreading;
import java.io.*;
import java.net.*;
/**
*
* #author Amanur Rahman
*/
public class SocketTreading {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5050);
System.out.println("Server is starting...");
int cn=1;
while (cn<=5) {
Socket s = ss.accept();
System.out.println("Client"+cn+" is connected \n" + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assinging new thread for this client");
Thread t = new ClientHandler(s, dis, dos);
t.start();
cn++;
}
System.out.println("Client limit cross");
ss.close();
}
}
class ClientHandler extends Thread {
final Socket soc;
final DataInputStream input;
final DataOutputStream output;
int i = 1;
public ClientHandler(Socket s, DataInputStream dis,
DataOutputStream dos) {
this.soc = s;
this.input = dis;
this.output = dos;
}
#Override
public void run() {
String received;
String ends;
String toreturn;
while (i <= 2) {
try {
output.writeUTF("Please write your message : ");
String str = input.readUTF();
System.out.println("Client msg is: "+ str.toUpperCase());
output.writeUTF("Do you want to exit or continue ( if exit type \"ENDS\" ) ");
ends = input.readUTF();
if (ends.equals("ENDS")) {
System.out.println("Client" + this.soc + "send exit.");
this.soc.close();
System.out.println("Connection closed");
break;
}
} catch (IOException e) {
System.out.println(e);
}
System.out.println("" + i);
i++;
}
try {
this.input.close();
this.output.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
// client side
package sockettreading;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Amanur Rahman
*/
public class ClientThreading {
public static void main(String[] args) throws IOException {
try(Socket s = new Socket("localhost", 5050);){
System.out.println("Connected");
Scanner scn = new Scanner(System.in);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
int i = 1;
while (i <= 2) {
System.out.println(dis.readUTF());
String num1 = scn.nextLine();
dos.writeUTF(num1);
System.out.println(dis.readUTF());
String num2 = scn.nextLine();
dos.writeUTF(num2);
System.out.println(dis.readUTF());
String ends = scn.nextLine();
dos.writeUTF(ends);
if (ends.equals("ENDS")) {
System.out.println("Closing the connection" + s);
s.close();
System.out.println("Connection closed");
break;
}
i++;
}
System.out.println(dis.readUTF());
s.close();
dos.close();
dis.close();
}
catch (IOException ex) {
if(ex.getMessage()!=null){
System.out.println("Already 5 clients are served so the server is closed: ");
}else{
System.out.println("Client 2 message already send. That's way the connection closed.");
}
}
}
}

Java Concurrent Socket Programming

Below is my code for a simple Concurrent Server. Whenever I run multiple clients, the server only prints out the input of the first client. I'm not sure what I've done wrong. Any help would be appreciated.
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
inputStream = new BufferedReader(new InputStreamReader(concurrentSocket.getInputStream()));
outputStream = new PrintWriter(new OutputStreamWriter(concurrentSocket.getOutputStream()));
String testString = inputStream.readLine();
System.out.println(testString);
} catch (IOException i){}
}
This code might help you to understand how to run multiple clients concurrently. :)
What this code does? TCP Client sends a string to the server and TCP server sends back the string in UPPERCASE format & the server can do this concurrently with multiple connections.
I have included 3 files for the server and one more for testing the server with multiple clients(ClientTest.java)
Main.java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
new Server(3000).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
public class Server {
private ServerSocket sSocket;
private boolean run;
private int port;
public Server(int port) throws IOException {
this.port = port;
this.sSocket = new ServerSocket(this.port);
}
public void start() {
this.run = true;
Logger.getLogger(getClass().getName()).info("Server is listening on port: " + port);
try {
while (run) {
Socket cs = sSocket.accept();
Logger.getLogger(getClass().getName())
.info("New Client Connected! " + cs.getPort());
new Thread(new Client(cs)).start(); // Put to a new thread.
}
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
public void stop() {
this.run = false;
}
}
Client.java (Client Process on server)
import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;
public class Client implements Runnable {
private Socket clientSocket;
private DataOutputStream out; // write for the client
private BufferedReader in; // read from the client
public Client(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
// Do client process
outToClient(inFromClient().toUpperCase());
closeConnection();
}
private String inFromClient() {
String messageFromClient = "";
/*
* Do not use try with resources because once -
* - it exits the block it will close your client socket too.
*/
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
messageFromClient = in.readLine();
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("InFromClientErr - " + e.getMessage());
}
return messageFromClient.trim().equals("") ? "No Inputs given!" : messageFromClient;
}
private void outToClient(String message) {
try {
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeBytes(message);
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("OutToClientErr - " + e.getMessage());
}
}
private void closeConnection() {
try {
in.close();
out.close();
clientSocket.close();
} catch (NullPointerException | IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
}
ClientTest.java (For Testing clients)
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket("localhost", 3000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(new Scanner(System.in).nextLine() + '\n'); // Get user input and send.
System.out.println(inFromServer.readLine()); // Print the server response.
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue was instead with the client. Not the server. The socket was declared outside of the for loop, and therefore only one connection was being created. Like so below:
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.1", 8001);
for (int i = 0; i < 5; i++){
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
The Socket should be declared inside the for loop like so:
public static void main(String[] args) {
try {
for (int i = 0; i < 5; i++){
socket = new Socket("127.0.0.1", 8001);
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
I really don't know why you need so complex structure of input and output streams. It is better to use Scanner that will wait for the new input.
Also you can use PrintWriter to output the results of your conversation.
Here is server that accepts multiple clients:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ConcurrentServer extends Thread {
private Socket concurrentSocket;
public ConcurrentServer(Socket clientSocket) {
this.concurrentSocket = clientSocket;
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
InputStream inputStream = concurrentSocket.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream outputStream = concurrentSocket.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
pw.println("message: " + line);
pw.flush();
}
} catch (IOException i){}
}
}

Server not getting data from client - JAVA

This is my server code:
package ServerSideHammingCodeCheckingAndResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private ServerSocket serverSocket;
private int port;
public Server(int port)
{
this.port = port;
}
public void start() throws IOException
{
System.out.println("Server starts at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
Socket client = serverSocket.accept();
sendMessage(client, "This is Hamming Code Checking.");
boolean checkInput = false;
String input = null;
while (!checkInput)
{
input = getMessage(client);
if(input.length() == 7 && input.matches("[01]+"))
checkInput = true;
else
sendMessage(client, "invalid");
}
sendMessage(client, input);
}
private void sendMessage(Socket client, String message) throws IOException
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
writer.flush();
writer.close();
}
private String getMessage(Socket client) throws IOException
{
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
userInput = reader.readLine();
return userInput;
}
public static void main(String[] args)
{
int portNumber = 9987;
try {
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is my client code:
package ClientSideDataTransmitter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client
{
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException
{
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("\nConnection Established.");
}
public void readResponse() throws IOException
{
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.print("Response from server: ");
while ((userInput = reader.readLine()) != null) {
System.out.println(userInput);
}
}
public void sendData() throws IOException
{
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
System.out.println("Enter a 7-bits binary as message to server:\n");
String input = sc.nextLine();
writer.write(input);
writer.flush();
}
public static void main(String arg[])
{
Client client = new Client ("localhost", 9987);
try {
client.connect();
client.readResponse();
client.sendData();
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
}
}
I havent finish up the code so please ignore minor mistakes in the code.
When I start Server, then Client, and send an input from Client to Server. Server seems not getting the data from Client since I send back that input from server to client to print it out, it prints nothing.
I think there may be problems in the method getMessage() in the server code but I cant fix it. Please help me fix the code. Many thanks!
Server:
Server starting at port 9987
Waiting for client...
Client:
Attempting to connect to localhost:9987
Connection Established.
Response from server: This is Hamming Code Checking.
Enter a 7-bits binary as message to server:
1234567
Response from server:
On top of Shriram suggestions I advise you to use PrintWriter here to avoid closing connection. It's also somewhat more convenient to use. Here's working example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
private int port;
public Server(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Server starts at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
Socket client = serverSocket.accept();
sendMessage(client, "This is Hamming Code Checking.");
boolean checkInput = false;
String input = null;
while (!checkInput) {
input = getMessage(client);
if (input.length() == 7 && input.matches("[01]+"))
checkInput = true;
else
sendMessage(client, "invalid");
}
sendMessage(client, input);
}
private void sendMessage(Socket client, String message) throws IOException {
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer.println(message);
}
private String getMessage(Socket client) throws IOException {
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
userInput = reader.readLine();
return userInput;
}
public static void main(String[] args) {
int portNumber = 9987;
try {
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("\nConnection Established.");
}
public void readResponse() throws IOException {
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.print("Response from server: ");
userInput = reader.readLine();
System.out.println(userInput);
}
public void sendData() throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter writer = new PrintWriter(socketClient.getOutputStream(), true);
System.out.println("Enter a 7-bits binary as message to server:\n");
String input = sc.nextLine();
writer.println(input);
}
public static void main(String arg[]) {
Client client = new Client("localhost", 9987);
try {
client.connect();
client.readResponse();
client.sendData();
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
}
}
The problem with your code is writer.close() in sendMessage() will internally close the writer objects. Your server program will be closed and no longer in connection to accept the connections.
You're losing data by creating a new BufferedReader per message. You need to use the same one for the life of the socket. Ditto 'PrintWriter` or whatever you use to send.

Exampels on a Server-Client-Chat applikation on JAVA [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I have been "googeling" around for a long time for examples over Server-client-chat application, but I can't really understand them. Many of them are using a class and creates the GUI from it, and I don't want to copy straight from it. Alot of examples doesn't either really explain how you send messages from a client to the server and then it sends the message out to all the other clients.
I am using NetBeans and I was wondering if there is some good tutourials or examples that can help me with this?
Here comes the multiThreading program :) the server has two classes, and client has one. Hope you Like it!
SERVER MAIN CLASS:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
int MAXCLIENTS = 20;
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
// An array of clientsConnected instances
ClientThread[] clientsConnected = new ClientThread[MAXCLIENTS];
try {
server = new ServerSocket(port);
System.out.println("listening on port: " + port);
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
clientSocket = server.accept();
} catch (IOException e) {
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
System.out.println("Client connected!");
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c] == null){
// if it is empty ( null) then start a new Thread, and pass the socket and the object of itself as parameter
(clientsConnected[c] = new ClientThread(clientSocket, clientsConnected)).start();
break; // have to break, else it will start 20 threads when the first client connects :P
}
}
}
}
}
SERVER CLIENT CLASS:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ClientThread extends Thread{
private ClientThread[] clientsConnected;
private Socket socket = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private String clientName = null;
//Constructor
public ClientThread(Socket socket, ClientThread[] clientsConnected){
this.socket = socket;
this.clientsConnected = clientsConnected;
}
public void run(){
try {
// Streams :)
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String message = null;
clientName = in.readUTF();
while (true){
message = in.readUTF();
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c]!= null && clientsConnected[c].clientName != this.clientName){ //dont send message to your self ;)
clientsConnected[c].sendMessage(message, clientName); // loops through all the list and calls the objects sendMessage method.
}
}
}
} catch (IOException e) {
System.out.println("Client disconnected!");
this.clientsConnected = null;
}
}
// Every instance of this class ( the client ) will have this method.
private void sendMessage(String mess, String name){
try {
out.writeUTF(name + " says: " + mess);
} catch (IOException e) {
e.printStackTrace();
}
}
}
AND FINALLY THE CLIENT:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
Main m = new Main();
m.connect();
}
public void connect() throws IOException{
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
System.out.print("Enter your name: ");
String name = keyboard.nextLine();
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//start a thread which will start listening for messages
new ReceiveMessage(in).start();
// send the name to the server!
out.writeUTF(name);
while (true){
//Write messages :)
String message = keyboard.nextLine();
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
class ReceiveMessage extends Thread{
DataInputStream in;
ReceiveMessage(DataInputStream in){
this.in = in;
}
public void run(){
String message;
while (true){
try {
message = in.readUTF();
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I ran the server in eclipse, and started two clients from the CMD, looks like this:
Here is a super simple I made just now with some comments of what is going on. The client connects to the server can can type messages which the server will print out. This is not a chat program since the server receives messages, and the client send them. But hopefully you will understand better it better :)
Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static DataInputStream in;
public static DataOutputStream out;
public static void main(String[] args) throws IOException {
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
try {
//start listening on port
server = new ServerSocket(port);
System.out.println("Listening on port: " + port);
//Accept client
clientSocket = server.accept();
System.out.println("client Connected!");
//initialize streams so we can send message
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
String message = null;
while (true) {
// as soon as a message is being received, print it out!
message = in.readUTF();
System.out.println(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
}
}
Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while (true){
System.out.print("\nMessage to server: ");
//Write a message :)
String message = keyboard.nextLine();
//Send it to the server which will just print it out
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
}

Multiple client server in which a client can only send message to server but server to all clients in java

I want that message sent by server should be delivered to all the clients however a message sent by by client should only be delivered to server.
Problem is when i run the code-
1.Server waits for client to connect
2.when multiple client connected
3.Now as the server broadcast the first message it is received by both the clients but when server broadcast the message second time. Both the clients has to send message in order to receive server message.
I am a noob in socket programming so please correct me what i am doing wrong?
So far i have made this program.
Server Code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class Server_Side3
{
static Client_server t[] = new Client_server[10];
static LinkedList<Client_server> al = new LinkedList<Client_server>();
public static void main(String args[]) throws IOException
{
ServerSocket server = null ;
Socket socket = null;
try
{
int Port =9777;
server = new ServerSocket(Port);
System.out.println("Waiting for Client " + server);
while(true)
{
socket = server.accept();
System.out.println("Connected to " + socket.getLocalAddress().getHostAddress());
Client_server clients = new Client_server(socket);
al.add(clients);
clients.start();
}
}
catch (Exception e)
{
System.out.println("An error occured.");
e.printStackTrace();
}
try
{
server.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static class Client_server extends Thread
{
Socket sockets;
PrintWriter out;
Client_server t[];
Client_server (Socket s )
{
sockets = s;
}
public void run()
{
try
{
InetAddress localaddr = InetAddress.getLocalHost();
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(sockets.getInputStream());
out = new PrintWriter(sockets.getOutputStream(),true);
String input = null;
while(true)
{
String servermsg = sc.nextLine();
broadcast(servermsg);
System.out.println("Message sent to client: "+servermsg);
input = in.nextLine();
System.out.println(localaddr.getHostName()+" Said :"+ input);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void broadcast(String servermsg)
{
Iterator it = al.iterator();
while(it.hasNext())
{
((Client_server) it.next()).send(servermsg);
}
}
private void send(String msg)
{
String servrmsg = msg;
out.println(msg);
out.flush();
}
}
}
Client Code :
import java.net.Socket;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ClientSide2
{
static Scanner chat = new Scanner(System.in);
public static void main(String[] args)
{
int Port = 9777;
String Host = "localhost";
try
{
Socket socket = new Socket(Host, Port);
System.out.println("You connected to "+ Host);
Scanner in = new Scanner(socket.getInputStream()); //GET THE CLIENTS INPUT STREAM
PrintWriter out = new PrintWriter(socket.getOutputStream());
String clientinput;
while(true)
{
System.out.println(in.nextLine());//If server has sent us something .Print it
clientinput=chat.nextLine();
out.println(clientinput); //SEND IT TO THE SERVER
out.flush();
}
}
catch (Exception e)
{
System.out.println("The server might not be up at this time.");
System.out.println("Please try again later.");
}
}
}

Categories

Resources