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);
Related
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);
}
}
}
}
Am writing a Server, client chat program using Java Socket. Here is my code for the Server socket class.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine();
output.println(inputLine);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
The client is able to make a connection and send a message to the server. The server can also receive the messages sent by the client. The problem is that when the message is sent from the server, the client does not receive the message. Here is my client socket code.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) throws Exception
{
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true)
{
System.out.println("Client: ");
line = clientInput.readLine();
output.println("Server: " + line );
if(line.equals("quit"))
{
break;
}
}
}
input.close();
clientInput.close();
output.close();
}
}
Server side:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8085);
} catch (IOException ex) {
System.out.println("IO Error, " + ex);
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Listening for incoming connections");
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Failed to accept connection " + ex);
System.exit(1);
}
System.out.println("Connection Successful");
System.out.println("Listening to get input");
PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
System.out.println("Client request: " + inputLine);
String resp = "some response as you need";
output.println(resp);
System.out.println("Server response: " + resp);
if (!inputLine.equals("exit")) {
} else {
break;
}
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
Client side:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
BufferedReader input;
PrintStream output;
BufferedReader clientInput;
try (Socket client = new Socket("127.0.0.1", 8085)) {
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
clientInput = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String inputStr = clientInput.readLine();
output.println(inputStr);
System.out.println("Client: " + inputStr);
if (inputStr.equals("quit")) {
break;
}
String serverResp = input.readLine();
output.println("Server: " + serverResp);
}
}
}
}
It is tested.
It's always a good idea to flush your output streams when you are done with them, the info you are sending may have buffered.
The server is expecting an extra line from the client input here:
while ((inputLine = input.readLine()) != null) {
System.out.println(inputLine);
System.out.println("Server: ");
inputLine = input.readLine(); // <--- here
The client is not reading from the InputStream called input it gets when it connects to the server. It is only reading the local console input from clientInput.
In the while loop in Client.java you need something like this after the quit block to get the server's response:
System.out.println("Server: " + input.readLine());
I wanna write the code to let Client send a string to Server, Server print the string and reply a string, then Client print the string Server reply.
My Server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
My Client:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
are there some somethings wrong? if i remove the code "while(true) ..." in client class, it's OK.
you should add "\r\n" at the end of the String which write into stream.
example:
client :
string = "end";
out.write(string + "\r\n");
out.flush();
server :
out.write("to end" + "\r\n");
out.flush();
out.close();
System.out.println("end");
// break;
I don't see the server response.
You do a
System.out.println("br: " + string);
but not a
out.write(string);
out.flush();
Appand "\n" to end of the response from server.
outToClient.writeBytes(sb.toString() + "\n");
You are reading lines but you aren't writing lines. Add a newline, or call BufferedReader.newLine().
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