I used Netbeans to write program but want to run in terminal to check wether socket programming is working or not. I was able to compile the first file ServerClient.java successfully but not able to run. here is my programming files
ServerProgram.java
package echoserver;
public class ServerProgram {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
ClientProgram.java
package echoserver;
public class ClientProgram {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java Client <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
){
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("socket: " + 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);
}
}
}
cmd:
Puja:echoserver pujadudhat$ javac ServerProgram.java
Puja:echoserver pujadudhat$ $javac ServerProgram.java -d
-bash: ServerProgram.java: command not found
Puja:echoserver pujadudhat$
Compile the code as follow:
$javac YourJavaFileName.java -d .
In your case: $javac ServerProgram.java -d ..
Then run as follow:
$java PackageName.ClassName
In your case: java echoserver.ServerProgram.
You can refer another similar question here.
Related
I am trying to write an IRC client that is very simple, with the hopes of later expanding it.
At this point I have two classes written in java that are supposed to work together and were copied from the Oracle tutorial. What I am trying to do is have the EchoClient connect to a host on a certain port so that the host running EchoServer can print out what the client types. I am trying to do exactly what the tutorial says that it does, but I am getting an error after copying and pasting the code.
EchoClient.java:
import java.io.*;
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> <port number>");
System.exit(1);
}
String hostName = args[0];
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);
}
}
}
EchoServer.java:
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]);
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
When I try to run the compiled EchoServer from my terminal with java EchoServer 2000 I get the error, Error: Could not find or load main class EchoClient and I get the same error from java EchoServer 2000
The Echo server example shows you how to do this. First set up an output stream of some sort, using the socket that the client creates:
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
Then when you have a message to send, write the result to the out object with println().
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
//...
}
You can find these lines in the code listing on the tutorial page: https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
This isn't the only way of writing to a socket, but that's how the example does it and you should probably stick with that for now.
If you are running your application from command prompt - try first opening cmd.exe as Administrator.
Type in windows start menu: cmd, Then right click on cmd.exe and choose "Run as Administrator".
Then in command prompt that opens execute
java knockclient 127.0.0.1 80 test
as you normally would.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to create a program where a client and server send text messages to each other (in utf-8 string format) similar to how two phones text message each other. Eventually I will need to create four lines (two to encode/decode utf-8 string on server side) (two to encode/decode utf-8 string on client side) This program uses two threads, one for the client one for the server.
Screenshot of error in mac terminal (command prompt)
There were no errors before I changed the following lines of code:
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
There are three files: the main function file, the server file, and the client file. When the main function file runs, if the "-l" command line argument is present, the server file will run, otherwise the client will run.
Server file (DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
private static Socket socket;
boolean KeepRunning = true;
void ServerRun(String[] args)
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
System.out.println("Port number is: " + port_number1);
ServerSocket serverSocket = new ServerSocket(port_number1);
//SocketAddress addr = new InetSocketAddress(address, port_number1);
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//Reading the message from the client
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
//Shut down with zero-length message
if(MessageFromClientDecodedFromUTF8.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
//creating message to server send from standard input
String newmessage = "";
try {
// input the message from standard input
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null && KeepRunning==true )
{
newmessage += line + " \n ";
}
}
catch ( Exception e ) {
System.out.println( e.getMessage() );
}
//Writing return message back to client
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Server.start();
}
}
Client file (DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
boolean KeepRunning = true;
private static Socket socket;
//static String[] arguments;
//public static void main(String[] args)
//{
// arguments = args;
//}
public DirectMessengerClient()
{
//System.out.println("test.");
}
public void ClientRun(String[] args)
{
Thread Client = new Thread ()
{
public void run()
{
System.out.println("Client thread is now running");
try
{
System.out.println("Try block begins..");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
while(KeepRunning)
{
String host = "localhost";
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);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
if(MessageFromServer.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Client.start();
}
}
Main function file (DirectMessengerCombined.java):
public class DirectMessengerCombined
{
public static void main(String[] args)
{
DirectMessengerClient Client1 = new DirectMessengerClient();
DirectMessengerServer Server1 = new DirectMessengerServer();
for (int i = 0; i < args.length; i++)
{
if(!args[0].equals("-l"))
{
Client1.ClientRun(args);
}
switch (args[0].charAt(0))
{
case '-':
if(args[0].equals("-l"))
{
Server1.ServerRun(args);
}
}
i=args.length + 20;
}
}
}
My question is: How do I change the way the strings are encoded or decoded in order to send strings to the other side or how to solve the null pointer exception error?
It is because you are trying to get the inputstream of a socket before it exists:-
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
These two lines should be the other way around. :)
EDIT: Looking further at your code, you are creating BufReader1 (which is causing the error) and then creating br in exactly the same way, i.e. both are a BufferedReader of the socket. You only need one; having two will probably cause problems for the readers.
I have used both a reader object and a scanner but while this client is connected to a simple socket server and they are both running, I cannot take an input from the user in the console and pass it to the server. pressing enter simply skips a line, scanner.nextLine() seems to capture nothing or something is going wrong when passing a variable to the output streamer.
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Socket socket = null;
DataOutputStream outputStream = null;
BufferedReader reader = null;
Scanner scan = new Scanner(System.in);
String message;
String host = "macbook";
int port = 9999;
//attempts to connect to given host and port
try {
socket = new Socket(host, port);
outputStream = new DataOutputStream(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host +".");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + host+".");
e.printStackTrace();
}
// if everything has been initialized then write some data
if (socket != null && outputStream != null && reader != null) {
try {
message=scan.nextLine();
outputStream.writeBytes(message);
String responseLine;
while ((responseLine = reader.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
//closes client once communication with server has ended
outputStream.close();
reader.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
I'm new to the world of Java and now I'm trying to create a socket program. I created a server and a client, but they didn't seem to work. Now I post the code.
This is the server:
import java.net.*;
import java.io.*;
public class TCPCmdServer
{
public int port;
public ServerSocket server;
TCPCmdServer (int port)
{
this.port = port;
if(!createServer())
System.out.println("Cannot start the server");
else System.out.println("Server running on port " + port);
}
public boolean createServer ()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdServer tcp = new TCPCmdServer(5000);
boolean flag = true;
while (flag)
{
try
{
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
String cmd = in.readLine();
System.out.println("Recieved: " + cmd);
if (cmd.equals("END"))
{
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
flag = false;
}
else
{
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null)
{
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
And this is the client:
import java.net.*;
import java.io.*;
public class TCPCmdClient
{
public Socket socket;
public int port;
public String ip;
TCPCmdClient (String ip, int port)
{
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else System.out.println("Connected to " + ip + ":" + port);
}
public boolean createSocket ()
{
try
{
socket = new Socket(ip, port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try
{
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag)
{
System.out.println("Type a command... type END to close the server");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END"))
{
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else
{
String outputline;
while ((outputline = in.readLine()) != null)
System.out.println(outputline);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
[old]
I believe the problem is with the input and output streams, but I can't understand why they don't work.
The expected behavior is as follows: The client connects to the server then the server send response. The client asks the user to insert a MS-DOS command (or a "END" command), the command is then sent to the server. The server executes the command on the computer where it is running (in case the command is END it closes the connection). Then the server sends the result of the command to the client, and the client displays it to the user.
[/old]
Now the only problem is that I have to close and re-open a client any time I like to execute a new command
In your server code, you are creating a new socket for every command you received from the client. That is why you have to open a new client every time you want to send a command to the server. To correct this, first you need to remove the while(flag) loop in server code. Then you can use the following to establish the connection to the client and send and receive command and output between them.
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
try {
while(!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null) {
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
}
In TCPCmdServer.java, try changing
out.write("Welcome on the server... type the commands you like, type END to close me");
to
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
Also, change
out.write(buffer.toString());
to
out.write(buffer.toString() + "\n");
out.flush();
In TCPCmdClient.java
change
out.write(cmd);
to
out.write(cmd + "\n");
out.flush();
response = in.readLine();
System.out.println("Server: " + response);
Hi guys i've written a simple telnet socket client in java and i'm trying to connect to the telnet services on localhost within windows 7 Pro. The code is executing fine but it is failing to printout out the the output stream and input stream instead the code trow the following exception:
Attemping to connect to host localhost on port 1024
Couldn't get I/O for the connection to: localhost
Is there something that i'm missing ??? THE CODE IS BELOW
Thanks in advance.
import java.io.*;
import java.net.*;
import java.util.*;
public class telnetClients {
public static void main(String[] args) throws IOException {
String telnetServer = new String ("localhost");
int port = 1024;
if (args.length > 0)
telnetServer = args[0];
System.out.println ("Attemping to connect to host " +
telnetServer + " on port "
+ port);
Socket ClientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
ClientSocket = new Socket(telnetServer, port);
ClientSocket.setSoTimeout(20000);
// PrintStream com = new PrintStream(ClientSocket.getOutputStream());
// System.out.println(com);
// BufferedReader inCom = new BufferedReader(new InputStreamReader (ClientSocket.getInputStream()));
out = new PrintWriter(ClientSocket.getOutputStream(), true);
System.out.println(out);
in = new BufferedReader(new InputStreamReader(
ClientSocket.getInputStream()));
String command = in.readLine();
if(in != null);
System.out.println(in);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + telnetServer);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + telnetServer);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"bye\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
// end loop
if (userInput.equals("bye"))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
ClientSocket.close();
}
}
sample for you which worked for me
public static void main(String[] args) {
String url = "hostname";
int port = 8080;
try (Socket pingSocket = new Socket(url, port)) {
try (PrintWriter out = new PrintWriter(pingSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()));) {
out.println("ping");
System.out.println("Telnet Success: " + in.readLine());
}
} catch (IOException e) {
System.out.println("Telnet Fail: " + e.getMessage());
}
}
I think that your problem is probably that the Telnet service is not enabled. In Windows 7 you can check this in Programs and Features (Control Panel) under Windows features.
After that you have to configure the port because the default port por a TCP connection is 23. You can do this with tlntadmn [\\server] config port=PortNumber