I am trying to send a json string from a client to a server. The code seems to send the string correctly from the client, but the server won't receive the code and print out the results. What am I doing wrong?
InputStream inp;
PrintStream ps = null;
while(true){
try{
ps = new PrintStream(socket.getOutputStream());
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
System.out.println("hello"); //This works
String input = brinp.readLine();
System.out.println(input); //Nothing is printed here
}
catch(IOException e){
System.out.println(e);
}
}
This is my server side code
//Socket s was initialized above
BufferedReader br;
DataOutputStream dos;
try {
dos = new DataOutputStream(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PatientStructure patient = new PatientStructure((int) (Math.random() * 10 + 1),
textFieldFirstName.getText(), textFieldLastName.getText(), new String[1]);
String sendString = gson.toJson(patient);
dos.writeBytes(sendString);
System.out.println("hello"); //This runs so my guess is that the above line has worked correctly
/**if (br.readLine().equals("ACCEPTED"))
dos.writeBytes(sendString + "/n");
else
System.out.println("Error");**/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Both programs are connected to the same socket and problem seems to be in these lines. Thanks in advance :)
Related
I have a Java server that listens to connections from a PHP client and replies back. My problem is I can't write anything to outputStream after reading the inputStream.
while (true)
try {
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
if (!clientSocket.getInetAddress().equals(clientSocket.getLocalAddress())) {
clientSocket.close();
continue;
}
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
LinkedList<String> messageFromPHP = new LinkedList<>();
String message = "";
while ((message = br.readLine()) != null)
messageFromPHP.add(message);
bw.write("test_message\n");
bw.flush();
bw.close();
br.close();
clientSocket.close();
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
ex.printStackTrace();
serverSocket.close();
}
^^ This makes both the PHP client and Java Server stuck forever. (I have added SoTimeout to the server to prevent that)
while (true)
try {
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
if (!clientSocket.getInetAddress().equals(clientSocket.getLocalAddress())) {
clientSocket.close();
continue;
}
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
LinkedList<String> messageFromPHP = new LinkedList<>();
String message = "";
while ((message = br.readLine()) != null) {
messageFromPHP.add(message);
bw.write("test_message\n");
bw.flush();
}
bw.close();
br.close();
clientSocket.close();
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
ex.printStackTrace();
serverSocket.close();
}
^^ However this one works perfectly fine and I don't know why. I'm sure these while loops end because I can print messageFromPHP without a problem with both codes.
So, how can I avoid doing everything inside the readLine loop?
Edit: To make things more clear: I want to write and read like the first code. But when I'm reading the input, I can't write to output so I have to use the second code and I don't want to. I'm trying to store the input inside the messageFromPHP list and write to output after that according to the input in the list.
I wrote a simple socket tutorial about sending/receive messages between client and server. I used DataOutputStream to write the string in stream but server couldn't read it if I used BufferedReader
If I use PrintWriter to write(client side), it works.
What's wrong here? Tks so much.
1. Client:
client = new Socket("localhost", 1982);
DataOutputStream opStr = new DataOutputStream(client.getOutputStream());
//pw = new PrintWriter(client.getOutputStream(), true);
//pw.println("Hello, is there anybody out there?");// Can be read by BufferedReader
opStr.writeUTF("Hello, anyone there?");
opStr.flush();// BufferedReader can't read it
2. Server:
openServer();// port 1982
while(true) {
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
DataInputStream inStr = new DataInputStream(
clientSocket.getInputStream());
//System.out.println("M1: Got msg " + inStr.readUTF());// It showed the content
BufferedReader bfReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("got Messages: ");
String strLine = "";
// Don't show anything
while ((strLine = bfReader.readLine()) != null) {
System.out.println(strLine);
}
}
You can't. If you use writeUTF() at one end, you have to use readUTF() at the other end.
You just have to decide which API you're going to use, instead of trying to mix and match them.
You want to read the files as either text e.g. BufferedReader OR binary e.g. DataInputStream. So you can't use both.
Server.java
public class Server
{
public static void main(String[] args)
{
DataInputStream inStr = null;
String str;
openServer();// port 1982
while(true)
{
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
try
{
inStr = new DataInputStream(clientSocket.getInputStream());
str = inStr.readUTF();
System.out.print((String) str);
System.out.flush();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
catch (Throwable anything)
{
System.err.println("Exception caught !: " + anything);
}
finally
{
if (inStr != null)
{
try
{
inStr.close();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
}
}
}
}
}
I have a Server-Client program where I send a small messsage to the client using JLabel. When that message is recieved from server that particular client must send a response immediately. But it is not sending any message . Can somebody look at my code and tell me where my mistake is?
//SERVER
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
while (true) {
socket = listener.accept();
socketList.add(socket);
//socketList.add(listener.accept());
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
}
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
}
//CLIENT
void connect_server() throws IOException
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
while(true){
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
if(answer != null)
{
PrintStream pr = new PrintStream(s.getOutputStream());
InputStreamReader rd = new InputStreamReader(System.in);
BufferedReader ed = new BufferedReader(rd);
String temp = ed.readLine();
pr.println(temp);
JOptionPane.showMessageDialog(null,"Answer is not null"); //THIS WORKS
}
}
}
catch (ConnectException e) {
JOptionPane.showMessageDialog(null, e);
}
catch (SocketException e) {
JOptionPane.showMessageDialog(null, e);
}
}
Some points that you missed in your implementation:
the streams and sockets are never closed
in the client i do not see the point of the endless loop
the client should initialize the communication by sending a message via output stream (not to try to read first)
For a simple example the steps should be:
Start sever to listen and once a connection is established to read the message (you did)
The client should sent a message via output stream and close the steams and the socket
The severs should close the streams and the sockect for the established connection
Example:
//Server
socket = listener.accept();
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream());
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
String msg = "Message received";
pr.write(msg,0,msg.length());
pr.newLine();
ed.close();
pr.close();
socket.close();
//Client
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(s.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sendMessage = "Send Message";
pr.write(msg,0,msg.length());
pr.newLine();
String answer = input.readLine();
System.out.println(answer);
JOptionPane.showMessageDialog(null,"Answer is not null");
input.close();
pr.close();
s.close();
UPDATE
reading from input stream continuously:
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line=input.readLine())!=null){
//do something with line
}
I will suggest a simple approach where server is sending the hi msg to client.
For server:
//Server
ServerSocket ss=new ServerSocket(3554);
socket = ss.accept();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getOutputStream()));
String msg ="Hi from server"
bw.write(msg);
String msgFromClient=br.readLine();
System.out.println(msgFromClient);
bw.close();
socket.close();
For Client:
//Client
Socket socket=new Socket("localhost",3554)
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String received = input.readLine();
System.out.println(received);
bw.write("Client recieve :"+received);
br.close();
bw.close();
socket.close();
i have this assignment where i am supposed to write a proxy server that uses java sockets to handle get requests from a client. I am now stuck and have been looking all over google to find the answer but without success.
Christoffers solution helped my with my first problem. Now that i have updated the code this is what i am using.
The problem is that it only downloads parts of most webpages before it gets stuck on sending the packets back to the client loop. At the moment I cant explain why it is behaving the way it is.
public class MyProxyServer {
//Set the portnumber to open socket on
public static final int portNumber = 5555;
public static void main(String[] args){
//create and start the proxy
MyProxyServer myProxyServer = new MyProxyServer();
myProxyServer.start();
}
public void start(){
System.out.println("Starting MyProxyServer ...");
try {
//create the socket
ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber);
while(true)
{
//wait for a client to connect
Socket clientSocket = serverSocket.accept();
//create a reader to read the instream
BufferedReader inreader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "ISO-8859-1"));
//string builder for preformance when we loop over the inputstream and read lines
StringBuilder builder = new StringBuilder();
String host = "";
for (String buffer; (buffer = inreader.readLine()) != null;) {
if (buffer.isEmpty()) break;
builder.append(buffer.replaceAll("keep-alive", "close"));
if(buffer.contains("Host"))
{
//parse the host
host = buffer.replaceAll("Host: ", "");
}
System.out.println(buffer);
}
String req = builder.toString();
System.out.println("finshed reading \n" + req);
System.out.println("host: " + host);
//new socket to send the information over
Socket s = new Socket(InetAddress.getByName(host), 80);
//printwriter to send text over the output stream
PrintWriter pw = new PrintWriter(s.getOutputStream());
//send the request from the client
pw.println(req+"\r\n");
pw.flush();
//create inputstream to receive the web page from the host
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
//create outputstream to send the web page to the client
BufferedOutputStream outbuffer = new BufferedOutputStream(clientSocket.getOutputStream());
byte[] bytebuffer = new byte[1024];
int bytesread;
//send the response back to the client
while((bytesread = in.read(bytebuffer)) != -1) {
System.out.println(bytesread);
outbuffer.write(bytebuffer,0, bytesread);
outbuffer.flush();
}
System.out.println("done sending");
//close the streams
inreader.close();
s.close();
pw.close();
outbuffer.close();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch(RuntimeException e){
e.printStackTrace();
}
}
}
If anyone could explain to me why i cant get it working correctly and how to solve it I would be very grateful!
Thanks in advance.
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...