I have written a Server Class, my client is my browser. When i enter localhost:8082in my browser, the hardcoded website www.mmix.cs.hm.eduis opened. So far so good.
A website normally has more than one page. My server is only able to retrieve the home page www.mmix.cs.hm.edu/index.html, regardless of if i click on the other links. I would like to be able to navigate to these other pages. Can anyone take a look at my code and give me a hint on how i can proceed?
public static void main(String args[]) {
String fromClient = "www.mmix.cs.hm.edu";
try(ServerSocket welcomeSocket = new ServerSocket(8082)){
System.out.println("Server started, waiting for clients...");
while(true){
StringBuilder htmlCode = new StringBuilder();
try(Socket connectionSocket = welcomeSocket.accept();
DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader fromBrowser = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()))){
try(InputStream url = new URL("http://"+fromClient+"/index.html").openStream();
BufferedReader getUrl = new BufferedReader(new InputStreamReader(url))){
for(String line = getUrl.readLine(); line != null; line = getUrl.readLine()){
htmlCode.append(line);
}
String str = htmlCode.toString();
toClient.writeBytes(str);
//toClient.write("\r\n");
}
}
}
}
catch(IOException io){
io.printStackTrace();
}
}
#ObiWanKenobi- Changed your code to extract the URL part. Try the below code snippet. Please go thru the comments in the code snippet. Run and confirm if the string manipulation works. Thanks.
public static void main(String args[]) {
String fromClient = "www.mmix.cs.hm.edu";
try(ServerSocket welcomeSocket = new ServerSocket(8082)){
System.out.println("Server started, waiting for clients...");
while(true){
StringBuilder htmlCode = new StringBuilder();
try(Socket connectionSocket = welcomeSocket.accept();
DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader fromBrowser = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()))){
String line1 = fromBrowser.readLine(); //Line 1 is of format: GET /index.html HTTP/1.1
String dynUrl = line1.substring(line1.indexOf(32)+1,line1.lastIndexOf(32)); //dynUrl is of format:/index.html
//Please note that the query string parameters not taken into account and the code may fail if the query string contains space character.
//Construct a new URL based on dynUrl
try(InputStream url = new URL("http://"+fromClient+dynUrl).openStream();
BufferedReader getUrl = new BufferedReader(new InputStreamReader(url))){
for(String line = getUrl.readLine(); line != null; line = getUrl.readLine()){
htmlCode.append(line);
}
String str = htmlCode.toString();
toClient.writeBytes(str);
//toClient.write("\r\n");
}
}
}
}
catch(IOException io){
io.printStackTrace();
}
}
Related
I'm trying to create a little program in Java which will allow me to access a remote Unix server, run some commands and then display the output of those commands in the IDE.
I've been smashing together bits of code and trying to learn how it works as I go along, which probably isn't ideal!
Currently, I'm able to run the commands from the console and I'm able to see the results on the server, but I've been unable to send the output back to the console. Whenever I try to send them back as a string, I'm getting something along the lines of java.lang.UNIXProcess$ProcessPipeInputStream#9x57d1ad instead of the usual output that I'm seeing on the server. I'm sure there's something obvious I'm doing wrong, but I'm a beginner and despite spending hours searching I've not been able to find a solution yet. I'd really appreciate some help. Thanks!
RUNNING ON SERVER:
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
if (inputLine.equals("storage")) {
runStorage();
printResults(runStorage()); }
catch (Exception e) {
e.printStackTrace();
}
public static Process runStorage() throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("df", "-h");
Process process = processBuilder.start();
printResults(process);
return process;
}
public static String printResults(Process process) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
return line; }
CLIENT:
public class ClientInitiator {
public static void main(String[] args) throws IOException, InterruptedException {
String hostName = "myHostNameGoesHere";
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()).equals("")) {
out.println(userInput);
if (userInput.equals("storage")) {
String serverResponse = in.readLine();
System.out.println(serverResponse);}
In order to get output of a running process, try the following code.
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
I am new to socket programming. I have to write a program where client accepts filename from a user and sends it to the server. The server reads corresponding file and sends its content back to client. Now my problem is server program freezes on 'String file = br.readLine()'. When I terminate my client program, further lines of server code get executed. If I comment out while loop at the end of my client code, server code works perfectly fine(it prints data to standard output). Can you tell what could be wrong with my code?
Server Code:
public class SocketServer {
public static void main(String[] args) throws Exception{
System.out.println("Server is started.");
ServerSocket ss = new ServerSocket(9999);
System.out.println("Server is waiting for a client.");
Socket server = ss.accept();
System.out.println("Client is connected.");
BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
String file = br.readLine();
System.out.println("Requested file is: " + file);
OutputStreamWriter os = new OutputStreamWriter(server.getOutputStream());
PrintWriter writer = new PrintWriter(os);
BufferedReader fr = new BufferedReader(new FileReader(file));
String line;
while((line = fr.readLine()) != null) {
writer.write(line);
writer.flush();
System.out.println(line);
}
}
}
Client Code:
public class SocketClient {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
Socket client = new Socket("localhost", 9999);
OutputStreamWriter os = new OutputStreamWriter(client.getOutputStream());
PrintWriter writer = new PrintWriter(os);
System.out.print("Enter filename: ");
String file = in.nextLine();
writer.write(file);
writer.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Content of " + file + ":");
String str;
while((str = br.readLine()) != null) {
System.out.print(str);
}
System.out.println("File transfer is complete.");
}
}
br.readLine(); will wait for input till it finds a new-line .
writer.write(file); You are writing file name without a new-line.
So in order to make it work either write a newline char at client or read it char by char at server.
Hope this helps.
I'm learning some Java socket programming and I've managed to make my first ever connection between Server and Client. That sparked a curiosity in me: what would happen if instead of the "Connected" and "Message Received" messages I made a sort of "chat room" type thing, where server and client inputs are printed to one another? So I tried doing just that.
Now, I know this isn't the way chat rooms are created (I'd probably need Threads and whatnot), but I was very curious as to why this didn't work:
Server:
public void run() throws Exception
{
boolean isChatting = true;
Socket clientSocket = new Socket("localhost", 444);
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
ps.println("Connected.");
BufferedReader bfr = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader bfrClient = new BufferedReader(new InputStreamReader(System.in));
String serverMessage = bfr.readLine();
String clientMessage;
System.out.println("Server: "+serverMessage);
while (isChatting)
{
clientMessage = bfrClient.readLine();
ps.println(clientMessage);
if (clientMessage.toUpperCase().equals("EXIT"))
{
isChatting = false;
}
}
bfr.close();
bfrClient.close();
}
Client:
public void run() throws Exception
{
boolean isChatting = true;
ServerSocket server = new ServerSocket(444); //Port
Socket sSocket = server.accept();
PrintStream ps = new PrintStream(sSocket.getOutputStream());
BufferedReader bfr = new BufferedReader(new InputStreamReader(sSocket.getInputStream()));
BufferedReader bfrPersonal = new BufferedReader(new InputStreamReader(System.in));
String clientMessage = bfr.readLine();
String messageToSend;
System.out.println("Client: "+clientMessage);
if (clientMessage != null)
{
ps.println("Connected.");
}
while (isChatting)
{
messageToSend = bfrPersonal.readLine();
ps.println(messageToSend);
if (messageToSend.toUpperCase().equals("EXIT"))
{
isChatting = false;
}
}
bfr.close();
bfrPersonal.close();
}
Thank you for your time! :)
If you like to create a chat system the easiest way is to create two threads on the server and two threads on the client side.
The first thread handle the input of the user and send it.
The second thread handle the input from the other chat system and print it.
I'm connecting to a remote TCP Listener that receives a string, and responds with a response.
Going from my Windows 8 Phone App, to a Java Jar. The Jar IS receiving the message, but the Windows 8 Phone App is not getting the response.
C# Code
outputClient.Connect (/IP ADDRESS/, /Port/);
using (Socket sock = outputClient.Client) {
sock.Send (UTF8Encoding.ASCII.GetBytes (broadcastMessage));
var response = new byte[100];
sock.Receive (response);
var str = Encoding.ASCII.GetString (response).Replace ("\0", "");
Console.WriteLine ("[RECV] {0}", str);
} <-- JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED
Java Code
String clientSentence;
ServerSocket socketServer = new ServerSocket(/* PORT */);
while (true)
{
Socket connectionSocket = socketServer.accept();
connectionSocket.setKeepAlive(true);
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
if (clientSentence != null)
{
try
{
JsonObject json = new JsonParser().parse(clientSentence).getAsJsonObject();
String un = json.get("Username").toString();
String uuid = "2c9c79a096ef4d869fb1d1e07469bb41".replaceAll(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5");
var val = /* Get val */
String response = gson.toJson(val);
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
}
connectionSocket.close();
}
A little more explanation: JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED means that the socket appears to not be sending until using (Socket sock = outputClient.Client) is no longer being used.
I fixed it by replacing the C# code with:
using (TcpClient client = new TcpClient (/IP ADDRESS/, /PORT/))
using (NetworkStream stream = client.GetStream ())
using (StreamReader reader = new StreamReader (stream))
using (StreamWriter writer = new StreamWriter (stream)) {
writer.AutoFlush = true;
foreach (string lineToSend in linesToSend) {
Console.WriteLine ("Sending to server: {0}", lineToSend);
writer.WriteLine (lineToSend);
string lineWeRead = reader.ReadLine ();
Console.WriteLine ("Received from server: {0}", lineWeRead);
Thread.Sleep (2000); // just for effect
}
Console.WriteLine ("Client is disconnecting from server");
}
i'm new to java. I'm trying to create a simple java file server from where the clients can request for a file and download it. basically when a client requests for a file it will simply will be written from server's folder to client folder. When i run my code it does not show any error but the file that client requested is not written to it's folder either.
my client side code:
public void download(Socket s) throws Exception {
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
System.out.print("Enter File Name :");
String request = con.readLine();
w.println(request);
String msg = r.readLine();
if (msg.startsWith("ERROR")) {
System.out.println("File not found on Server ...");
return;
} else if (msg.startsWith("FOUND")) {
System.out.println("Receiving File ...");
File f = new File(request);
if (f.exists()) {
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option = con.readLine();
if (Option == "N") {
dout.flush();
return;
}
}
FileOutputStream fileout = new FileOutputStream(f);
int ch;
String temp;
do {
temp = din.readLine();
ch = Integer.parseInt(temp);
if (ch != -1) {
fileout.write(ch);
}
} while (ch != -1);
fileout.close();
System.out.println(din.readLine());
}
}
The server side:
public class Fileagent extends Thread {
Socket client;
DataInputStream din;
DataOutputStream dout;
ServerSocket soc;
PrintWriter w;
BufferedReader r;
public Fileagent(Socket soc) {
try {
client = soc;
din = new DataInputStream(client.getInputStream());
dout = new DataOutputStream(client.getOutputStream());
w = new PrintWriter(client.getOutputStream(), true);
r = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
System.out.println("FTP Client Connected ...");
start();
} catch (Exception ex) {
}
}
public void upload() throws Exception {
w.println("SEnding.....");
String file = r.readLine();
File f = new File(file);
if (!f.exists()) {
w.println("ERROR");
return;
} else {
w.println("FOUND");
FileInputStream fin = new FileInputStream(f);
int ch;
do {
ch = fin.read();
w.println(String.valueOf(ch));
} while (ch != -1);
fin.close();
}
I'm trying to send simple text files but the files is not being send to clients.
Thanks in advance.
I suspect the problem is that you are not flushing your PrintWriter after sending the request from the client to the server:
w.println(request);
w.flush();
You seem to be using a PrintWriter on the server side as well. Make sure to call w.flush() or w.close() when you are done sending stuff over.
Also, I assume you realize that this is an extremely inefficient way to send the file over.
It looks like your problem stems from this
String request=con.readLine();
You're always reading from this con object. But you're passing in a Socket s to the method.
There are other problems, such as what Gray mentioned, and also that you're writing each character on its own line, but those are just messed up formatting; they shouldn't prevent you from getting a file at all...