I have a program ready that acts as a client and another that acts as a server.
I want to be able to send a message to the server, and the server will then forward the message to another client that is also connected to the server.
So the the server is supposed to forward the message to the other client.
How would i be able to do that, and what do I need to read up on?
This is what i got now.
Server.java
package server;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server{
public static void run() {
ServerSocket serverSocket = null;
Socket socket = null;
try{
while(true){
serverSocket = new ServerSocket(5555);
socket = serverSocket.accept();
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String message = bufferedReader.readLine();
System.out.println(message);
if(message != null){
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println("Message receivd!");
}
streamReader.close();
socket.close();
serverSocket.close();
bufferedReader.close();
}
}catch(Exception e){}
// try{
//
// }catch(Exception e){}
}
public static void main(String[]args){
Server s = new Server();
s.run();
}
}
And then I also got TCPClient.java
package client;
import java.net.*;
import java.io.*;
public class TCPClient {
private String serverIP = "localhost";
private int serverPort = 1111;
private int count = 0;
private Thread thread;
public TCPClient() {
this.thread = new Thread(new ConnectAndListenToServer());
// thread.start();
}
public void sendMessage(int count){
this.count = count;
this.thread = new Thread(new ConnectAndListenToServer());
thread.start();
}
private class ConnectAndListenToServer implements Runnable {
Socket socket = null;
public void run() {
BufferedReader bufferedReader = null;
InputStreamReader streamReader = null;
try {
socket = new Socket(serverIP,serverPort);
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println(count);
streamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(streamReader);
String message = bufferedReader.readLine();
if(message != null){
System.out.println(message);
}
}catch(Exception e){}
try{
socket.close();
bufferedReader.close();
streamReader.close();
}catch(Exception ee){}
}
}
}
How would i be able to forward the messeage already received on the server to another client?
How would i be able to forward the messeage already received on the server to another client?
I have already posted some samples in the same context.
Till now you have done well, to complete it please have a look Client-Server Communication. I have described it step by step just follow the thread to find other samples as well.
Please let me know if still you have any issue!
This just works if you have Client 2 connected while Client 1 is also connected.
This is possible if you write a multithreading application or use a Selector.
Related
my server class
import java.net.*;
import java.io.*;
public class server
{
private Socket socket;
private ServerSocket server;
// constructor with port
public void start(int port){
try {
server = new ServerSocket(port);
while(true){
socket = server.accept();
new ConnectionHandler(socket).run();
}
}catch(IOException i){
}
}
}
class ConnectionHandler implements Runnable{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public ConnectionHandler(Socket socket){
this.socket=socket;
}
#Override
public void run() {
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try
{
System.out.println("Waiting for a client ...");
System.out.println(server);
System.out.println("Client accepted");
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String[] args) {
server serverr = new server();
serverr.start(4000);
}
}
Here's my client class.
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 4000);
}
}
Trying to develop pretty simple chat application works via terminal, but I think there are plenty of bugs I have in my code.
The server can handle one client, but when another client comes up it doesn't connect to other clients.
What am I have to do now?
I couldn't find out where my problem is, waiting your helps.
Note: I am completely new to socket programming concept.
The ConnectionHandler class is a thread class, and you must wrap its object to a Thread instance and then call start() instead of run().
So in the Server class change
new ConnectionHandler(socket).run();
with
new Thread(ConnectionHandler(socket)).start();
I recently wrote a socket communication program in java where two threads run concurrent on each server and client side handling the read and write operations to the socket allowing continuous message sending and receiving on both sides.
The problem is either of the client or the server stops receiving communication from the other side and then after a while both of them stop working. I can't figure out what's wrong and how the connection is dropping :/
Code for server
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private Scanner inp = null;
String line = "";
String iline = "";
public Server(int port)
{
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
out=new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
inp = new Scanner(System.in);
while (true)
{
new Thread(new Runnable(){
public void run()
{
try{
while(true){
line = in.readUTF();
System.out.println("Client : "+line);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown())
{
System.out.println("DED");
System.exit(0);
}
}
}
catch(Exception e){
System.out.println("Exception !!!");
}
}
}).start();
iline=inp.nextLine();
out.writeUTF(iline);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown()){
System.out.println("DED");
System.exit(0);
}
}
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
Code for Client
import java.net.*;
import java.io.*;
import java.util.Scanner;
class Client{
private Socket socket =null;
private DataInputStream inp=null;
private DataOutputStream out=null;
private Scanner in=null;
String line="";
String iline="";
Client(String address,int port)
{
try{
socket = new Socket(address,port);
in= new Scanner(System.in);
out = new DataOutputStream(socket.getOutputStream());
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
while(true){
line=in.nextLine();
out.writeUTF(line);
new Thread(new Runnable(){
public void run()
{
try{
while(true){
iline=inp.readUTF();
System.out.println("Server : "+iline);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown()){
System.out.println("DED");
System.exit(0);
}
}
}
catch(Exception e){
System.out.println("Exception !!!");
}
}
}).start();
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown()){
System.out.println("DED");
System.exit(0);
}
}
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(Exception e){
System.out.println("EXCEPTION!!!");
}
}
}
class ClientSocket{
public static void main(String...args){
Client obj = new Client("127.0.0.1", 5000);
}
}
Just an initial run through your code what I see is in the first while(true){} , you are spawning a thread calling start method on it . The moment you start the reading thread the main thread checks fo sockets conditions and moves ahead. Since there is a true in your first while(true) a new thread is again spawned and that goes on an on until the socket is closed where the programs terminates because of system.exit call.
Can someone look at my code and tell me what's wrong?
I am trying to make a client server chat program and want server to accept endless connections requested from the clients. It runs successfully. At First run, server and client are able to chitchat properly but when the client is closed(quit) and again came back, client is able to connect with
server and even it can send messages to server and messages are also received by the server BUT there is issue at server side, At Server side server messages are not reach to client properly. Some messages are skipped and are not able to reached to client immediately as it was before in the first run.Please help me if anyone can find this solution.
SERVER CODE:
//packages
import java.io.*;
import java.net.*;
import java.lang.*;
public class Server1 {
public static void main(String[] args) throws IOException {
// Instance variable fields
ServerSocket listener=null;
Socket clientSocket=null;
final int port = 444;
System.out.println("Server waiting for connection on port "+port);
try
{
listener = new ServerSocket(port);
// Creates a server socket bound to the specified port.
}
catch(IOException e)
{
e.printStackTrace();
}
while(true)
{
try
{
clientSocket = listener.accept(); //Listens for a connection to be made to this socket and accepts it.
//clientsocket is now the route through which we can communicate with the client.
//if we reach here, the server got a call already...
System.out.println("You have succesfully connected");
/*Returns local address of this serversocket and
Returns the remote port number to which this socket is connected. */
System.out.println("Recieved connection from "+clientSocket.getInetAddress() +" on port "+clientSocket.getPort());
new echoThread(clientSocket).start(); //new thread for a client
}
catch( IOException e)
{
System.out.println("I/O error "+e);;
}
}
}
}
class echoThread extends Thread{
Socket clientSocket; // instance variable field
//For every client we need to start separate thread.
public echoThread(Socket clientSocket) //constructor
{
this. clientSocket = clientSocket;
}
//create two threads to send and recieve from client
public void run()
{
RecieveFrmClientThread recieve = new RecieveFrmClientThread(this.clientSocket);
Thread thread = new Thread(recieve);
thread.start();
SndToClientThread send = new SndToClientThread(this.clientSocket);
Thread thread2 = new Thread(send);
thread2.start();
}
}
//INCOMING
class RecieveFrmClientThread implements Runnable
{
Socket clientSocket=null;
BufferedReader br = null;
public RecieveFrmClientThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
} //end constructor
public void run() {
try{
br = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
//returns the input stream through which the server can hear the client.
String messageString="";
System.out.println("Please enter something to send back to client..");
while(true){
while((messageString = br.readLine())!= null)
{//assign message from client to messageString
if(messageString.equals("EXIT"))
{
System.out.println("you have been logout from it");
//break;//break to close socket if EXIT
}
System.out.println("From Client: " + messageString);//print the message from client
messageString="";
}
}
}
catch(Exception ex){System.out.println(ex.getMessage());}
}
}//end class RecieveFromClientThread
//OUTGOING
class SndToClientThread implements Runnable
{
//instance field variables
PrintWriter pwPrintWriter;
Socket clientSock = null;
public SndToClientThread(Socket clientSock)
{
this.clientSock = clientSock;
}
public void run() {
try{
pwPrintWriter =new PrintWriter(this.clientSock.getOutputStream(),true);//returns the output stream through which the server can talk to the client,
while(true)
{
String msgToClientString = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));//get input from server
msgToClientString = input.readLine();//read message from server to send it to client
if(msgToClientString.equals("EXIT"))
{
System.out.println("Disconnecting Client!!");
//System.exit(0);
}
pwPrintWriter.println(msgToClientString);//send message to client with PrintWriter
pwPrintWriter.flush();//flush the PrintWriter
}//end while
}
catch(Exception ex){System.out.println(ex.getMessage());}
}//end run
}//end class SendToClientThread
CLIENT CODE :
import java.io.*;
import java.net.*;
public class Client1 {
//Instance variable field
//private ServerSocket ss;
public static void main(String[] args)
{
try {
Socket sock = new Socket("localhost",444);
/*//create two threads to send and recieve from client
RecieveFromServer recieveThread = new RecieveFromServer(sock);
System.out.println("SOCK=" +sock);
Thread thread2 =new Thread(recieveThread);
thread2.start();
SendToServer sendThread = new SendToServer(sock);
Thread thread = new Thread(sendThread);
thread.start();*/
new echoThread1(sock).start(); //new thread for a client
}
catch (Exception e) {System.out.println(e.getMessage());}
}
}
class echoThread1 extends Thread {
Socket sock;
public echoThread1(Socket sock) {
this.sock = sock;
}
//create two threads to send and recieve from client
public void run()
{
RecieveFromServer recieveThread = new RecieveFromServer(this.sock);
Thread thread = new Thread(recieveThread);
thread.start();
SendToServer sendThread = new SendToServer(this.sock);
Thread thread2 = new Thread(sendThread);
thread2.start();
}
}
class RecieveFromServer implements Runnable
{
Socket sock=null;
BufferedReader recieve=null;
public RecieveFromServer(Socket sock) {
this.sock = sock;
}//end constructor
public void run() {
try{
recieve = new BufferedReader(new InputStreamReader(sock.getInputStream()));//get inputstream for this socket
String msgRecieved = null;
while((msgRecieved = recieve.readLine())!= null)
{
System.out.println("From Server: " + msgRecieved);
}
}catch(Exception e){System.out.println(e.getMessage());}
}//end run
}//end class RecieveFromServer
class SendToServer implements Runnable
{
Socket sock=null;
PrintWriter print=null;
BufferedReader brinput=null;
public SendToServer(Socket sock)
{
this.sock = sock;
}//end constructor
public void run(){
try{
if(this.sock.isConnected()) //Returns TRUE if the socket is successfuly connected to a server
{
System.out.println("Client connected to "+this.sock.getInetAddress() + " on port "+this.sock.getPort());
this.print = new PrintWriter(sock.getOutputStream(), true);
System.out.println("Type your message to send to server..type 'EXIT' to exit");
while(true){
brinput = new BufferedReader(new InputStreamReader(System.in)); // input from client
String msgtoServerString=null;
msgtoServerString = brinput.readLine();
this.print.println(msgtoServerString);
this.print.flush();
if(msgtoServerString.equals("EXIT"))
{
System.out.println("you have logged out of server...Thanks for your visit");
sock.close();
break;}
}
}//end while
}
catch(Exception e){System.out.println(e.getMessage());}
}//end run method
}//end class SendToServer
I am trying to figure out why I can send messages to the client from the server but when I try the other way around (to send messages from the client to the server) the program halts like it is waiting for some action to happen.
also how to prevent the sockets from being closed immediately.
this is the code:
Client Class
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
Client aClient = new Client();
aClient.run();
}
private Socket socket;
private PrintWriter toServer;
private BufferedReader fromServer;
public void run() {
try {
socket = new Socket("localhost", 9000);
if (socket.isConnected()){
System.out.println("CONNECTED");
}
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(socket.getOutputStream());
toServer.print("hello server");
System.out.print(fromServer.readLine());
toServer.close();
socket.close();
} catch (Exception error) {
System.out.println("CLIENT ERROR: " + error);
}
}
}
Server Class
import java.io.*;
import java.net*;
public class Server {
public static void main(String[] args) {
Server aServer = new Server();
aServer.run();
}
private ServerSocket mainSocket;
private Socket socket;
private PrintWriter toClient;
private BufferedReader fromClient;
public Server(){
try{
mainSocket = new ServerSocket(9000);
}
catch (Exception error){
System.out.print("Error :"+error);
}
}
public void run() {
System.out.println("WAITING FOR CLIENTS");
try {
socket = mainSocket.accept();
if(socket.isConnected()) {
System.out.println("CONNECTED.");
}
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new PrintWriter(socket.getOutputStream());
System.out.println(fromClient.readLine());
toClient.print("hello Client");
toClient.close();
}
catch (Exception error) {
System.out.println("SERVER ERROR :" + error);
}
}
}
Add this before toServer.print("hello server"); to Client class. Its read from System.in and send to the Server class:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromUser;
while((fromUser = stdIn.readLine()) != null) {
System.out.println("Client: " + fromUser);
toServer.println(fromUser);
}
And to Server class add this, before System.out.println(fromClient.readLine());, its read line from client and print to System.out:
String inputLineFromClient;
while ((inputLineFromClient = fromClient.readLine()) != null) {
System.out.println(inputLine);
}
Socket not closing before you invoke method close() or occurs some Exception.
your server is not reading anything.
use
fromClient.readLine();
basically what i want to do is develop a chat program(something between an instant messenger and IRC) to improve my java skills.
But I ran into 1 big problem so far: I have no idea how to set up streams properly if there is more than one client. 1:1 chat between the client and the server works easily, but I just don't know what todo so more than 1 client can be with the server in the same chat.
This is what I got, but I doubt its going to be very helpful, since it is just 1 permanent stream to and from the server.
private void connect() throws IOException {
showMessage("Trying to connect \n");
connection = new Socket(InetAddress.getByName(serverIP),27499);
showMessage("connected to "+connection.getInetAddress().getHostName());
}
private void streams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n streams working");
}
To read from multiple streams in one program, you're going to have to use multithreading. Because reading from streams is synchronous, you'll need to read from one stream for each thread. See the java tutorial on threads for more info on multithreading.
I've done this several times with ServerSocket(int port) and Socket ServerSocket.accept(). This can be pretty simple by having it listen to the one port you want your chat server client listening on. The main thread will block waiting for the next client to connect, then return the Socket object to that specific client. Usually you'll want to put them in a list to generically handle n-number of clients.
And, yes, you will probably want to make sure each Socket is in a different thread, but that's entirely up to you as the programmer.
Remember, there is no need to re-direct to another port on the server, by virtue of the client using a different source port, the unique 5-tuple (SrcIP, SrcPort, DstIP, DstPort, TCP/UDP/other IP protocol) will allow the one server port to be re-used. Hence why we all use stackoverflow.com port 80.
Happy Coding.
Made something like that a few months back. basically I used a separate ServerSocket and Thread per client server side. When client connects you register that port's input and output streams to a fixed pool and block until input is sent. then you copy the input to each of the other clients and send. here is a basic program run from command line:
Server code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
static int PORT_NUMBER = 2012;
public static void main(String[] args) throws IOException {
while (true) {
try (ServerSocket ss = new ServerSocket(PORT_NUMBER)) {
System.out.println("Server waiting #" + ss.getInetAddress());
Socket s = ss.accept();
System.out.println("connection from:" + s.getInetAddress());
new Worker(s).start();
}
}
}
static class Worker extends Thread {
final static ArrayList<PrintStream> os = new ArrayList(10);
Socket clientSocket;
BufferedReader fromClient;
public Worker(Socket clientSocket) throws IOException {
this.clientSocket = clientSocket;
PrintStream toClient=new PrintStream(new BufferedOutputStream(this.clientSocket.getOutputStream()));
toClient.println("connected to server");
os.add(toClient);
fromClient = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
#Override
public void run() {
while (true) {
try {
String message = fromClient.readLine();
synchronized (os) {
for (PrintStream toClient : os) {
toClient.println(message);
toClient.flush();
}
}
} catch (IOException ex) {
//user discnnected
try {
clientSocket.close();
} catch (IOException ex1) {
}
}
}
}
}
}
Client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
final BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
PrintStream toUser = System.out;
BufferedReader fromServer;
final PrintStream toServer;
Socket s = null;
System.out.println("Server IP Address?");
String host;
String port = "";
host = fromUser.readLine();
System.out.println("Server Port Number?");
port = fromUser.readLine();
s = new Socket(host, Integer.valueOf(port));
int read;
char[] buffer = new char[1024];
fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
toServer = new PrintStream(s.getOutputStream());
new Thread() {
#Override
public void run() {
while (true) {
try {
toServer.println(">>>" + fromUser.readLine());
toServer.flush();
} catch (IOException ex) {
System.err.println(ex);
}
}
}
}.start();
while (true) {
while ((read = fromServer.read(buffer)) != -1) {
toUser.print(String.valueOf(buffer, 0, read));
}
toUser.flush();
}
}
}