Java - i am making a server which sends client latest updates - java

So i have this class, this class has the string i want in my other file(String Message)
Which picks up the message from the server. I am not sure how to get the string into another package and class. any help would be amazing
public class Client
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 43594;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//String number = "2";
String number = ClientSettings.ClientSettings.ClientVersion;
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println(""+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine(); //this is the string i need to get...
System.out.println("" +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Define in the class that need to use the "message" a private String (with getter/setter methods)
public class UseMessage{
private String message;
private static UseMessage instance;
private UseMessage(){
}
public static UseMessage getInstance(){
if(instance==null){
instance = new UseMessage();
}
return instance;
}
public String getMessage(){
return message;
}
public String setMessage(String message){
this.message = message;
}
}
Then in class Client:
UseMessage.getInstance().setMessage(br.readLine());
If you need in another class:
String message = UseMessage.getInstance().getMessage();
Thake a look here

Related

Java BufferedWriter when connected to server - null pointer exception - chat app

It's a simple chat app. Server and client as separately app.
Connection between server and client works fine. I have a problem when i'm trying to send String from Client by BufferedWriter to Server BufferedReader. I have null pointer exception.
And can you tell me that is everything fine with threads logic in this app ?
Server app
public class Server {
private int port = 5000;
private ServerSocket server = null;
private Socket socket = null;
private InputStreamReader isr = null;
private OutputStreamWriter osw = null;
private BufferedReader br = null;
private BufferedWriter bw = null;
private Chat chat;
private String message;
private int bOffset = 10;
private JFrame mainFrame;
private JPanel mainPanel;
private JPanel boxPanel;
private JLabel boxTitleLabel;
private JTextArea incomingMessagesJTextArea;
private JTextField messageWritten;
private JButton sendServerButton;
public static void main(String[] args){
System.out.println("Server is running");
new Server().createGUI(); //some swing GUI things
new Server().createServerConnection();
}
public void createServerConnection(){
try {
/** Create socket for communication between apps */
server = new ServerSocket(port);
socket = server.accept();
System.out.println("Server accept client: OK");
/** Create output writers */
osw = new OutputStreamWriter(socket.getOutputStream());
bw = new BufferedWriter(osw);
/** Create inputs readers */
isr = new InputStreamReader(socket.getInputStream()); //data in bytes format
br = new BufferedReader(isr); //data in character format
} catch (IOException e) {
System.out.println("Server Error createServerConnection(): " +e.getMessage());
}
/** Create new thread for read server-input data */
new Thread(new Runnable() {
public void run() {
System.out.println("Server Thread - running");
while (true) {
try {
String message = br.readLine();
System.out.println(message);
} catch (IOException e) {
System.out.println("Server Error createServerConnection() -> new Thread: " +e.getMessage());
}
}
}
}
).start();
}}
Client app
public class Client {
private int port = 5000;
private Socket socket = null;
private InputStreamReader isr = null;
private OutputStreamWriter osw = null;
private BufferedReader br = null;
private BufferedWriter bw = null;
private String message;
private int bOffset = 10;
private JFrame mainFrame;
private JPanel mainPanel;
private JPanel boxPanel;
private JLabel boxTitleLabel;
private JTextArea incomingMessagesJTextArea;
private JTextField messageWritten;
private JButton sendServerButton;
public static void main(String[] args){
System.out.println("Client is running");
new Client().createGUI(); //some swing GUI things
new Client().createConnectionWithServer();
new Client().sendTextToServer();
}
public void sendTextToServer(){
try {
message = "test";
bw.write(message); //null pointer exception
bw.write('\n');
bw.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public void createConnectionWithServer(){
try {
/** Create socket for communication between apps */
socket = new Socket("localhost", port);
/** Create inputs readers */
isr = new InputStreamReader(socket.getInputStream()); //data in bytes format
br = new BufferedReader(isr); //data in characters format
/** Create output writers */
osw = new OutputStreamWriter(socket.getOutputStream());
bw = new BufferedWriter(osw);
} catch (IOException e) {
System.out.println("Server Error createConnectionWithServer(): " +e.getMessage());
}
/** Create new thread for read client-input data */
new Thread(new Runnable() {
public void run() {
System.out.println("Client Thread - running");
while (true) {
try {
message = br.readLine();
System.out.println(message);
} catch (IOException e) {
System.out.println("Client Error createServerConnection() -> new Thread: " +e.getMessage());
}
}
}
}
).start();
}}
Change your main method to create a unique instance of your Client class:
public static void main(String[] args){
Client client = new Client();
System.out.println("Client is running");
client.createGUI(); //some swing GUI things
client.createConnectionWithServer();
client.sendTextToServer();
}
You were creating a new instance of the Client class everytime you called the "new" statement. Doing so the variable were initialized in the fist instance, making impossible for the other one to acces the initialized variable (throwing NullPointerException)

Access class or singleton from other activities

So I have network socket class that should be handling my socket connection that i want running when my app is running. Problem is I dont know how to reference the class other than just starting a new one.
To start a new one I would do:
Networker network = null;
try {
network = new Networker(SERVER_IP, SERVERPORT);
new Thread(network).start();
Then i could do:(from the same activity I just did the above in)
network.send("helloworld");
How can i do a network.send in any class without making a whole new socket connection?
Edit:
Here is my Networker Class:
public class Networker implements Runnable, Closeable {
private final Socket clientSocket;
private final PrintWriter out;
private final BufferedReader in;
private volatile boolean closed = false;
public Networker(String hostname, int port) throws IOException {
clientSocket = new Socket(hostname, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public void run() {
try {
for(String fromServer; (fromServer = in.readLine()) != null;)
System.out.println("Server: " + fromServer);
} catch (IOException ex) {
if (!closed)
Log.i("logging", "error") ;
}
}
public void send(String line) {
out.println(line);
}
public void close() {
closed = true;
try { clientSocket.close(); } catch (IOException ignored) { }
}
}

How do i send the message to multiple clients in java Client-Server Program

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
}

send from client to server and from server to client in java

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

Java Server And Client Socket Need Fix

Hello, I am new to java socket programming and I was just looking to see if somebody could give me some help.
I will post the code for the client and server then i will explain my problem...
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
while(running)
{
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
stream = new PrintStream(socket.getOutputStream());
stream.println("return: " + line);
}
}
}catch(IOException e)
{
System.out.println("Socket in use or not available: " + port);
}
}
public static void main()
{
run();
}
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintStream stream;
public static BufferedReader reader;
public static void main(String args[])
{
try
{
socket = new socket(ip, port);
stream = new PrintStream(socket.getOutputStream());
stream.println("test0");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
stream.println("test1");
line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
}catch(IOException e)
{
System.out.println("could not connect to server!");
}
}
So my problem is even if I get rid of the loop and try to make it send the string twice it won't send it. It will only do it once unless I close and make a new socket on the client side. So if anybody could give me an explanation to what I am doing wrong that would be great, and thank you so much.
Why are you openning your outstream inside your loop?
stream = new PrintStream(socket.getOutputStream());
Take this statement outside the loop and write to your stream inside your loop.
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket:
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");
Make sure you flush the output from your server:
stream.flush();
Thanks a lot to everybody who answered but i figures out what it was all along.
i read through some of the Oracle socket stuff and figured out that the server was supposed to be the first to send a message than the client receive and send and receive... so on and so forth so i will post my new code here in hopes somebody else trying to figure out the same thing can find it with ease
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintWriter print;
public static BufferedReader reader;
public Client(String ip, int port)
{
this.ip = ip;
this.port = port;
//initiate all of objects
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 5000);
print = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//start connection with server
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
//quick method to send message
public void sendMessage(String text)
{
print.println(text);
print.flush();
try
{
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
client.sendMessage("test");
client.sendMessage("test2");
client.sendMessage("test3")
}
//Server
public static int port = 9884;
public static boolean running = true;
public static ServerSocket serverSocket;
public static Socket socket;
public static PrintWriter writer;
public static BufferedReader reader;
public static void run()
{
try
{
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("connection");
while(running)
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
writer.println(line);
writer.flush();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
run();
}

Categories