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

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)

Related

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) { }
}
}

Sending bulk messages to all clients

I would like to know, how to send messages to all connected clients. To be more specific - to all ServerThreads.
Here are my classes:
public class Client {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("127.0.0.1", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromUser, fromServer;
while (!(fromUser = stdIn.readLine()).equalsIgnoreCase("#quit")) {
out.println(fromUser);
fromServer = in.readLine();
System.out.println(fromServer);
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
Server: http://pastebin.com/ZpBydK58
ServerThread: http://pastebin.com/CwAM72c3
Assign each new ServerThread to a array. Then you can make a method in Server that loops through the ServerThread array and sends a message to each, and in ServerThread make a method to send a message.
Example:
public class Server {
public final static int maxClients = 10000;
public final static ServerThread[] clients = new ServerThread[maxClients];
public static int numOfClients = 0;
public static ServerSocket server;
public static void main(String[] args){
try{
server = new ServerSocket(4444);
while (numOfClients<maxClients){
clients[numOfClients+1] = new ServerThread(server.accept());
numOfClients++;
clients[numOfClients].start();
}
while (true){
server.accept().close();
}
}catch(Exception error){error.printStackTrace();}
}
public static void sendMessage(String message){
for (int i=0;i<numOfClients;i++){
clients[i].sendMessage(message);
}
}
}

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 Socket Programing

Problem:
I have written one java socket server which send response when I send first message from the client to it. But I want to send one more message based on the first response. After the first response i am not getting any other response?
Here is the Server code:
public class SendSmsServerSocket {
private final static CxpsLogger logger = CxpsLogger.getLogger(SendSmsServerSocket.class);
SendSmsServerSocket(){
try {
new SeverSocketForSms(new ServerSocket(4330));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class SeverSocketForSms extends Thread {
private Socket socket;
private ServerSocket serversocket;
private volatile static boolean running = true;
public SeverSocketForSms(ServerSocket ssocket) throws IOException {
this.serversocket = ssocket;
start();
}
public void run() {
try{
while(running) {
this.socket = serversocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String msg = br.readLine();
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("inside SeverSocketForSms: msg received is : "+msg);
}
}
catch(Exception e){
e.printStackTrace();
}
catch(Throwable t) {
System.out.println("Caught " + t + "xmlServerThread - closing thread");
}
}
public static void shutdown() {
System.out.println("Stopping socket connection and thread");
try{
socket.close();
}catch (Exception e) {
e.printStackTrace();
}
running = false;
}
public static void main (String [] args){
try {
System.out.println("Starting sms server ----- Please press Enter Key to stop the server after receiving one message");
SendSmsServerSocket s=new SendSmsServerSocket();
new Scanner(System.in).nextLine();
SeverSocketForSms.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Once you have an incoming connection, you should delgate the responsibility for handling that incoming connection to another Thread, otherwise you will block your "accept" thread until the current connection is closed...
while (running) {
this.socket = serversocket.accept();
Thread thread = new Thread(new Handler(socket));
thread.start();
}
And the Handler
public class Handler implements Runnable {
private Socket socket;
public Handler(Socket socket){
this.socket = socket;
}
public void run() {
// You may need to add a repeat and exit clause here...
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String msg = br.readLine();
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("inside SeverSocketForSms: msg received is : " + msg);
}
}

Swing Socket Testing

I am trying a program with Swing.
I am using a socket to connect to the server, and the client has the gui code.
public class FactClient extends JFrame implements ActionListener
{
Socket s;
InputStream in;
OutputStream os;
Scanner sin;
PrintWriter out;
JPanel jp;
JTextField jt;
JButton jb;
JLabel jl;
FactClient()
{
jp = new JPanel();
jt = new JTextField("Enter number",15);
jb = new JButton("Compute Factorial");
jl = new JLabel("Answer");
jb.addActionListener(this);
jp.add(jt);
jp.add(jb);
jp.add(jl);
add(jp);
setVisible(true);
setSize(200,100);
try
{
s = new Socket("localhost",8189);
try
{
in = s.getInputStream();
os = s.getOutputStream();
sin = new Scanner(in);
out = new PrintWriter(os);
out.println("Done with the bingo");
}
finally {}
}
catch(Exception e)
{
System.out.println("Error in client code " + e );
}
}
public void actionPerformed(ActionEvent ae)
{
try {
System.out.println("Connection established " + jt.getText());
String t = jt.getText();
out.println("Ashish");
System.out.println("Data Send");
t = sin.nextLine();
jl.setText(t);
}
catch(Exception e)
{
System.out.println("Error in client code " + e );
}
}
public static void main(String args[])
{
new FactClient();
}
}
import java.io.*;
import java.util.*;
import java.net.*;
public class FactServer
{
public static void main(String args[])
{
ServerSocket s;
Socket socket;
try
{
s= new ServerSocket(8189);
socket = s.accept();
try
{
InputStream in = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Scanner sin = new Scanner(in);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
PrintWriter ou = new PrintWriter(os);
System.out.println("Connection Established : Stream initailzed");
try
{
String data = br.readLine();
System.out.println("Data Recvd." + data);
data = br.readLine();
}
catch(Exception e)
{
System.out.println("EEEEEEEEEEEEE" + e);
}
//int fact = data +20;
ou.println("40");
}
catch (Exception e)
{
System.out.println("ERROR :P");
}
finally
{
socket.close();
}
}
catch(Exception e)
{
System.out.println("ERROR" + e);
}
}
}
The server code simply reads the data that I send using System.out.println. But the problem is it hangs up; the server never gets the data!
out.println("Done with the bingo");
This is the first string that server should get. But it stays in the wait state as if nothing is received.
You must use flush() after each println() or activate automatic flushing on the PrintWriter so the data gets really sent:
...
out = new PrintWriter(os);
out.println("Done with the bingo");
out.flush();
...
or
...
out = new PrintWriter(os, true); // autoflush
out.println("Done with the bingo");
...
don't forget the server...
Enabling autoflush in your PrintWriter as Carlos said should solve your main question. A couple of other thoughts you might consider:
Wrap the server logic in a loop (e.g. while(true) {...}) if you want it to handle multiple client requests, and handle each request in a separate thread.
Since you are making the client request on the Swing Event Dispatch Thread (i.e. the actionPerformed() method) you might consider wrapping it in a Runnable or SwingWorker so you don't block the dispatch thread. Otherwise you might notice the UI appear to hang or not paint while the socket communication is happening.

Categories