I am trying to pass message from server to client in terminal. What I would like the program to do is, in the client, it should be able to enter a command, get response from server, and be able to enter another command without restarting Client (by java Client).
Client.java
Socket socket = new Socket(host, port);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String response = "";
boolean continuation = true;
while(continuation) {
Scanner input = new Scanner(System.in);
String command = (input.nextLine()).toString();
bw.write(command+"\r\n");
bw.flush();
if(command.equals("cmd1") {
while ((response = br.readLine()) != null) {
System.out.println(response);
}
}
System.out.println("This line will not execute as well.");
}
Server.java
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String[] in = br.readLine().split("\\s+");
String command = in[0];
if(command.equals("cmd1")) {
String response = "";
response = response + "RESPONSE:\r\n";
response = response + "This is a response.\r\n";
bw.write(response);
bw.flush();
}
If I don't put while((response = br.readLine()!= null) { ... } in Client.java, it is possible to enter multiple inputs in the terminal, but if I put it, it prints the response from the server and another input cannot be done without restarting Client.
Any help would be appreciated.
Thanks
This should work:
server:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
boolean continuation = true;
while (continuation) {
String command = dis.readUTF();
//proceeed command
dos.writeUTF("response");
dos.flush();
}
Client:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("your command");
while (dis.available() == 0) {
try {
//wait for response
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(RandomTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
String response = dis.readUTF();
//and so on
Related
i'm writing a java program that sends and receives data from a printer, i can get the command but i can't read in any way a response.
Socket s = new Socket(ip, port);
System.out.println("-----------------> MioSocket closed: "+s.isClosed());
OutputStream out = s.getOutputStream();
System.out.println("-----------------> InputStream: "+out.toString());
DataOutputStream output = new DataOutputStream(out);
String str = "GST\r";
output.writeUTF(str);
System.out.println("---->");
InputStream input = s.getInputStream();
System.out.println("-----------------> InputStream: "+input.toString());
InputStreamReader reader = new InputStreamReader(input);
System.out.println("-----------------> InputStream: "+reader.toString());
int character;
StringBuilder data = new StringBuilder();
System.out.println(reader.read());
while ((character = reader.read()) != -1) {
data.append((char) character);
}
System.out.println(data);
s.close();
I am trying to write a java server and client such that the client sends the server a POST request with some xml string read from a file as payload, the server fetches the request from the client and sends it an acknowledgment, and this process repeats till all the xml strings that the client has have been sent (as separate POST requests).
I have made the code for 1 single exchange of request and response between the client and server. But I am unable to extend it for multiple requests from the same client because the client waits for server's response and the server's response is not sent to the client till I write wr.close() or socket.close() after writing bytes in the DataOutputStream object. But as soon as I write either of the two commands, my connection between the server and client closes and the client needs to establish connection all over again in order to send the second request.
This is my server side function that receives the request and sends the response:
public HTTPServer(int port) {
try {
private ServerSocket server = new ServerSocket(port);
private Socket socket = server.accept();
int ind = 0;
while (ind<19) {
//socket is an instance of Socket
InputStream is = socket.getInputStream();
InputStreamReader isReader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isReader);
//code to read and print headers
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
ind++;
//send response to the client
Date today = new Date();
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
DataOutputStream wr = new DataOutputStream(socket.getOutputStream());
wr.writeBytes(httpResponse);
wr.flush();
}
socket.close(); // or wr.close()
} catch (IOException i) {
System.out.println(i);
}
}
This is my client side code:
public void postMessage() throws IOException {
// string to read message from input
File folder = new File("path/to/my/files");
String[] listOfFiles = folder.list();
for (int i = 0; i < listOfFiles.length; i++) {
File file = new File(listOfFiles[i]);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final URL url = new URL("http://localhost:8080");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
// Send post request
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
String line = "";
while (sc.hasNextLine()) {
line += sc.nextLine();
line += '\n';
}
wr.writeBytes(line);
wr.flush();
wr.close();
// read response
BufferedReader in;
if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
}
}
Unless I write socket.close() or wr.close() after wr.flush(), my response is not sent to the client and the client keeps waiting for it, but as soon as I do, the server socket is closed and the code terminates. How can I send response to my client without having to close the socket?
EDIT:
This is updated HTTP Client code, which uses sockets to send HTTP request, but the error persists.
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getByName("localhost");
Socket socket = new Socket(addr, 8080);
boolean autoflush = true;
// string to read message from input
File folder = new File("/Users/prachisingh/IdeaProjects/requests_responses");
String[] listOfFiles = folder.list();
for (int i = 0; i < listOfFiles.length; i++) {
System.out.println("File " + listOfFiles[i]);
File file = new File("/Users/prachisingh/IdeaProjects/requests_responses/" + listOfFiles[i]);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "";
while (sc.hasNextLine()) {
line += sc.nextLine();
line += '\n';
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send an HTTP request to the web server
out.println("POST / HTTP/1.1");
out.println("Host: http://localhost:8080");
out.println(line);
out.println();
// read the response
boolean loop = true;
StringBuilder sb = new StringBuilder(8096);
while (loop) {
if (in.ready()) {
int r = 0;
while (r != -1) {
r = in.read();
sb.append((char) r);
}
loop = false;
}
}
System.out.println(sb.toString());
}
socket.close();
}
Can anybody help me with this here. I am a newbie and I am working on a network application where I have to create a socket connection to the IP address and port that they already given me and then send XML message to the socket and finally include the ReadMe.txt file where I will save what I have received from the server. Here's my code
private static Socket socket;
public static void main(String args[])
{
try
{
socket = new Socket( "196.37.22.179", 9011);
//Send the message to the server
//PrintStream outstrm = null;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String str;
str = "<request>";
str += "<EventType>Authentication</EventType>";
str += "<event>";
str += "<UserPin>12345</UserPin>";
str += "<DeviceId>12345</DeviceId>";
str += "<DeviceSer>ABCDE</DeviceSer>";
str += "<DeviceVer>ABCDE</DeviceVer>";
str += "<TransType>Users</TransType>";
str += "</event></request>";
bw.write(str);
bw.flush();
System.out.println("Message sent to the server......! ");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
You can use this code to store results from server in file
//Get the return message from the server
InputStream is = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("ReadMe.txt"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
I need to make these code's multithreaded. I searched everywhere but i cant figure it out. Can you guys do it for me ?
Client.java's main method
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String senddata;
try{
clientSocket = new Socket("localhost",5555);
}catch(IOException e){
System.out.println("Connection Error!");
}
out = new PrintWriter(clientSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
BufferedReader data = new BufferedReader(new InputStreamReader(System.in));
while(!(senddata = data.readLine()).equals("STOP")){
out.println(senddata);
System.out.println("Response The Client = " + in.readLine());
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
}
out.close();
in.close();
data.close();
clientSocket.close();
Server.java's main method
ServerSocket serverSocket = null;
Socket clientSocket = null;
String receivedData;
try{
serverSocket = new ServerSocket(5555);
}catch(IOException e){
System.out.println("Port Error!");
}
clientSocket = serverSocket.accept(); // Bağlantıyı Sağlayan Kod Satırı. Bağlantı Sağlanmadan Bir Alt Satıra Geçilmez.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); // Clienta Veri Gönderimi İçin PrintWriter Nesnesi Oluşturuldu!
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Clientden Gelen Verileri Tutan BufferedReader Nesnesi Oluşturuldu!
while(!(receivedData = in.readLine()).equals("STOP")){
System.out.println("------------------------------------------------------------\nReceived Data From Client = " + receivedData);
System.out.println("Response = " + receivedData);
out.println(receivedData);
}
out.close();
in.close();
serverSocket.close();
clientSocket.close();
I have two simple classes:
Client:
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName(null);
Socket socket = null;
try {
socket = new Socket(addr, 1050);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
in = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter( socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, false);
stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
// read user input
while (true) {
userInput = stdIn.readLine();
System.out.println("Send: " + userInput);
out.println(userInput);
out.flush();
String line = in.readLine();
while(line != null){
System.out.println(line);
line = in.readLine();
}
System.out.println("END");
}
}
catch (UnknownHostException e) {
// ...
} catch (IOException e) {
// ...
}
// close
out.close();
stdIn.close();
socket.close();
}
Server:
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter out = new PrintWriter(bw, /*autoflush*/true);
private void sendMessage(String msg1, String msg2) {
out.println(msg1);
// empy row
out.println("");
out.println(msg2);
}
The user enters a message, and this is sent to the server. Then, the server responds with N messages.
After the first request, the client stops and is never printed the word "END".
How do I send multiple messages at different times, with only one socket connection?
Firstly, you don't need to send an empty row, because you are sending by "line" and recieving by "line".
out.println(msg1);
out.println(msg2);
and
userInput = stdIn.readLine();
Here, userInput will only equal msg1
What I would recommend, would be not to loop on stdIn.readLine() = null, but have the client send, for example, "END_MSG", to notify the server that it will not send anymore messages.
Perhaps something like...
SERVER:
userInput =stdIn.readLine();
if(userInput.Equals("START_MSG");
boolean reading=true;
while(reading)
{
userInput=stdIn.readLine();
if(userInput.Equals("END_MSG")
{
//END LOOP!
reading = false;
}
else
{
//You have received a msg - do what you want here
}
}
EDIT:CLIENT:
private void sendMessage(String msg1, String msg2) {
out.println("START_MSG");
out.println(msg1);
out.println(msg2);
out.println("END_MSG");
}
(It also looks like in your question to have mixed up the client and the server?)