How to debug "run time 1" error in Java? - java

I am new to Java and I would like to run this code but every time it says error run time 1!
Also, would someone advise me to use specific program to run Java code?
import java.net.*;
import java.io.*;
public class ChatServer
{ private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done)
{ try
{ String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(".bye");
}
catch(IOException ioe)
{ done = true;
}
}
close();
}
catch(IOException ioe)
{ System.out.println(ioe);
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
public static void main(String args[])
{ ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}

Why do you use a DataInputStream when you just want to read lines of text? Try a BufferedReader instead.

Related

How to broadcast messages to all clients using tcp in java

I am building a multithreaded chat server application which broadcasts a message sent by one client to all the clients.On most of the examples on internet and on Oracle's website too broadcasting is done using udp (Multicast Socket)but i am using tcp .
Does anyone know how to send a message to all the connected clients in a tcp conection?
Here is my current code which works fine and sends the message receieved from a client to that client only:
EchoServer
import java.net.*;
import java.io.*;
public class EchoServer
{
public static void main(String[] args)
throws IOException
{
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
while (true) {
try {
Thread t = new Thread(new MultiServer(serverSocket.accept()));
t.start();
} catch(IOException e) {
System.out.println("Accept Failed:");
System.exit(-1);
}
}
}
}
EchoClient
import java.io.*;
import java.util.Scanner;
import java.net.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
if (args.length != 2) {
System.err.println("Usage: java EchoClient <host name><portnumber>");
System.exit(1);
}
String hostName = "localhost";
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo::" + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
}
MultiServer
import java.io.*;
import java.net.*;
public class MultiServer implements Runnable
{
private Socket client;
public MultiServer(Socket m)
{
this.client = m;
}
#Override
public void run()
{
BufferedReader in = null;
PrintWriter out = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch(IOException ignored) {
}
while (true) {
String line;
try {
while ((line = in.readLine()) != null)
out.println(line);
} catch (IOException e) {
System.out.println("Read Failed");
System.exit(-1);
}
}
}
}
Use the concurrent hashmap and maintain your list of clients in that.
The concurrent hashmap is safe and you won't need to use synchronization while adding / iterating / removing
// Create and main list of active clients based on their host name / ip address
ConcurrentHashMap<String, Socket> activeClients = new ConcurrentHashMap<String, Socket>();
// message received
activeClients.put(clientsocket.getInetAddress().getHostAddress(), clientsocket);
// broadcast message to all available clients
for(String clientHost : activeClients.keySet()) {
// get each socket here and send a message to them.
}
Vector is basically a thread safe one so you don't need to worry about that one.

Chat Server Client Output

I am new to java. I am using NetBeans 8.0.2
I started a new project (Java -> Java Class Libary)
I have put two classes and run my code. There are no errors however, there is no output showing after building the project successfully.
I really appreciate your help.
My first class is ChatServer & my second one is ClientServer!
import java.net.*;
import java.io.*;
public class ChatServer
{ private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done)
{ try
{ String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(".bye");
}
catch(IOException ioe)
{ done = true;
}
}
close();
}
catch(IOException ioe)
{ System.out.println(ioe);
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
public static void main(String args[])
{ ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}
import java.net.*;
import java.io.*;
public class ChatClient
{ private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
public ChatClient(String serverName, int serverPort)
{ System.out.println("Establishing connection. Please wait ...");
try
{ socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
}
catch(UnknownHostException uhe)
{ System.out.println("Host unknown: " + uhe.getMessage());
}
catch(IOException ioe)
{ System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals(".bye"))
{ try
{ line = console.readLine();
streamOut.writeUTF(line);
streamOut.flush();
}
catch(IOException ioe)
{ System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void start() throws IOException
{ console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop()
{ try
{ if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
}
catch(IOException ioe)
{ System.out.println("Error closing ...");
}
}
public static void main(String args[])
{ ChatClient client = null;
if (args.length != 2)
System.out.println("Usage: java ChatClient host port");
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}
You need to run both ChatClient and ChatServer (hence the main methods in both classes).
Additionally, you need to pass command-line arguments. Let's take a look at main() in ChatClient:
public static void main(String args[])
{ ChatClient client = null;
if (args.length != 2)
System.out.println("Usage: java ChatClient host port");
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
You're parsing the arguments to retrieve a server name and a port. This is an example of running those classes with proper parameters:
java ChatServer 55444
java ChatClient 127.0.0.1 55444
Here is a short tutorial covering the issue of setting command-lind arguments in the Netbeans IDE.
Also, as #BDL pointed out, you'd better create a New Project instead of a java library (or even two projects for both a server and a client respectively).

simple client - server talking to each other classes in Java

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();

Why it is refusing the connection for second time?

I am trying to forward a message from a client to a server and again from that server to another server. For the first time it works fine but when I type second message its say "Unexpected exception: Connection refused" why is it so?
Here is the code
Client.java
import java.net.*;
import java.io.*;
public class Client {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
#SuppressWarnings("deprecation")
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals("exit")) {
try {
line = console.readLine();
streamOut.writeUTF(line);
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void start() throws IOException {
console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop() {
try {
if (console != null)
console.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public static void main(String args[]) {
#SuppressWarnings("unused")
Client client = null;
if (args.length != 2)
System.out.println("Usage: java Client host port");
else
client = new Client(args[0], Integer.parseInt(args[1]));
}
}
AuServer.java
import java.net.*;
import java.io.*;
public class AuServer {
private Socket socket = null;
private Socket publishingsocket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
private String line = null;
private DataOutputStream streamOut = null;
public AuServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done) {
try {
line = streamIn.readUTF();
System.out.println(line);
done = line.equals("exit");
} catch (IOException ioe) {
done = true;
}
forward(line, 50090);
}
close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void forward(String line, int port) {
try {
publishingsocket = new Socket("localhost", port);
streamOut = new DataOutputStream(publishingsocket.getOutputStream());
streamOut.writeUTF(line);
streamOut.flush();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
} finally {
try {
publishingsocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
}
public static void main(String args[]) {
#SuppressWarnings("unused")
AuServer server = null;
if (args.length != 1)
System.out.println("Usage: java Server port");
else
server = new AuServer(Integer.parseInt(args[0]));
}
}
AppServer.java
import java.net.*;
import java.io.*;
public class AppServer {
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
public AppServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done) {
try {
String line = streamIn.readUTF();
System.out.println(line);
done = line.equals("exit");
} catch (IOException ioe) {
done = true;
}
}
close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
}
public static void main(String args[]) {
#SuppressWarnings("unused")
AppServer server = null;
server = new AppServer(50090);
}
}
Pls help............
A typically socket server would require some kind of loop where in the server socket would accept incoming connections and spawn a new Thread which would be responsible for actually handling the new Socket connection, leaving the current thread free to continue processing any new incoming connections, for example...
server = new ServerSocket(port);
while (continueAccpetingConnections) {
Socket socket = server.accept();
Thread thread = new Thread(new SocketHandler(socket));
thread.start();
}
The SocketHandler would implement Runnable and provide a constructor that would accept a Socket variable.
It would then be the responsibility of the SocketHandler to actually perform the communications required by the server.
Now, if you wanted to have only one active connection, you might use
while (continueAccpetingConnections) {
Socket socket = server.accept();
process(socket);
}
Which would prevent any new connections until process returned...
Your server is written to accept exactly one connection, process it in the same thread, and then exit. If you want to keep accepting connections, do so, in a loop. If you want to handle clients concurrently, start a new thread to handle each accepted socket.

Java Sockets - A Client that reads the data the server gets

I am working on a java socket program and have difulcites with the client part. The server get's what all the clients write, but the client only gets what it writes. Could someone provide me with an example of a client part of a program that gets what all the clients write? Thanks!
Here is an "echo server" example
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws IOException
{
ServerSocket serverSocket = null;
DataInputStream serverInput = null;
PrintStream serverOutput = null;
String line = null;
Socket clientSocket = null;
// create server socket
try
{
serverSocket = new ServerSocket(2012);
clientSocket = serverSocket.accept();
serverInput = new DataInputStream(clientSocket.getInputStream());
serverOutput = new PrintStream(clientSocket.getOutputStream());
}
catch(IOException e){System.out.println(e);}
// receive data and send it back to the client
try
{
while(true)
{
line = serverInput.readLine();
if(line.equals("exit"))
{
break;
}
else
{
if(!line.equals(null) && !line.equals("exit"))
{
System.out.println("Received " +line);
line = line+" MODIFIED";
serverOutput.println(line);
}
}
}
}
catch(IOException e){System.out.println("SERVER SIDE: Unable send/receive data");}
try
{
serverInput.close();
serverOutput.close();
clientSocket.close();
serverSocket.close();
}
catch(IOException e){System.out.println(e);}
}
}
Here is the client
import java.io.*;
import java.net.*;
public class TCPClient
{
public static void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2012);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
if(userInput.equals("exit"))
break;
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}

Categories