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.
Related
This is my simple server program with java's ServerSocket class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
while (true)
{
try {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client...on " + port);
Socket client = server.accept();
System.out.println("Client from /" + client.getInetAddress() + " connected.");
BufferedReader rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
Writer out = new OutputStreamWriter(client.getOutputStream());
String nameClient = rdr.readLine();
System.out.println("Client " + nameClient + " wants to start a game.");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
I am trying to run config the server
but it keeps on saying this "Usage: java StartServer ".
I want to know how can I config the port when the port is args[0].
This is in Eclipse, by the way.
If it keeps saying "Usage: java StartServer" it therefore means this code
System.err.println("Usage: java StartServer <port>");
Is always been executed which means the condition
args.length != 1
Is always true. This could mean args.length = 0 or args.length > 1
Did you make eclipse pass the port number when running your application? That is did you configure any command line arguments to be used? I'm not a user eclipse so I can't help you here. See if this tutorial is helpful http://www.concretepage.com/ide/eclipse/how-to-pass-command-line-arguments-to-java-program-in-eclipse or you could try to find some other tutorial.
Also make sure you didn't pass too many arguments than is required because that will also make the condition to return true. Just pass as many arguments to make the condition args.length != 1 fail which is having 1 argument.
You can also see this question with help configuring command line arguments in eclipse.
This is my practice for you.
Copy and complete your code.
Select menu clicking right button of your mouse, Run > Run Configurations
Select Arguments tab and type a port number whatever you want your server to wait for client connection then, run it.
Test it with your client socket program.
This is my practice using client socket programming.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleClientSocketTest {
public static void main(String[] args) {
BufferedReader rdr = null;
Socket sock = null;
PrintWriter out = null;
try{
sock = new Socket("localhost", 9999);
rdr = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
out = new PrintWriter(sock.getOutputStream(), true);
String toServer = "hello...";
out.println(toServer + "i wants to start a game.");
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
if(fromServer == null) System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
rdr.close();
out.flush();
out.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Send a message to the server first,
out.println(toServer + "i wants to start a game.");
then, receive from the server.
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
There is one more thing to tell you about your server program.
This is a customized version of yours.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
while (true) {
BufferedReader rdr = null;
PrintWriter out = null;
int clientConnectionCnt = 0;
try {
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
if(client.isConnected())
{
System.out.println("Client from /" + client.getInetAddress() + " connected.");
String nameClient = null;
try {
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
System.out.println("clientConnectionCnt....." + clientConnectionCnt++);
nameClient = rdr.readLine();
out.println("Yes, You can");
if(nameClient == null) break;
System.out.println("Client: " + nameClient);
} catch (IOException e) {
e.printStackTrace();
break;
} finally {
out.flush();
rdr.close();
out.close();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
try {
server.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
First, you should create a server socket outside of while statement not in a while.
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
Just wait in a while statement util client socket accepting.
while (true) {
.... skip ...
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
Then, create in/out stream of client socket.
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
Finally, read and write a message with the socket's stream.
nameClient = rdr.readLine();
out.println("Yes, You can");
Regards, Rach.
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.
I am writing a client-server program in java using TCP/IP. For the purpose, I wrote the following codes:
serversock.java:
import java.net.*;
import java.io.*;
public class serversock {
public static void main(String[] args) throws IOException
{
ServerSocket sersock = null;
try
{
sersock = new ServerSocket(10007);
}
catch (IOException e)
{
System.out.println("Can't listen to port 10007");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Waiting for connection....");
try
{
clientSocket = sersock.accept();
}
catch ( IOException ie)
{
System.out.println("Accept failed..");
System.exit(1);
}
System.out.println("Conncetion is established successfully..");
System.out.println("Waiting for input from client...");
PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = input.readLine();
while ( inputLine != null)
{
output.println(inputLine);
System.out.println("Server: " + inputLine);
inputLine = input.readLine();
}
input.close();
clientSocket.close();
sersock.close();
}
}
clientsock.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class clientsock
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost",10007);
// Scanner scan = new Scanner(System.in);
PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
String line = null;
BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter data to send to server: ");
line = stdInput.readLine();
while ( (line) != "bye")
{
output.println(line.getBytes());
line = stdInput.readLine();
System.out.println("Server sends: " + input.read());
}
sock.close();
}
}
Now on running the programs I got the following output:
server:
shahjahan#shahjahan-AOD270:~/Documents/java$ java serversock
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B#4e25154f
shahjahan#shahjahan-AOD270:~/Documents/java$
client:
shahjahan#shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server:
qwe
sdf
^Cshahjahan#shahjahan-AOD270:~/Documents/java$
The server is recieving different symbols, and client receives nothing. Please help me to solve it.
In the client replace:
output.println(line.getBytes());
with
output.println(line);
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