Start doPost method in java servlet from arduino using ethernetclient - java

I've got a java tomcat servlet with a doPost method and a webpage running on that server. I set up a very basic test with a html button on my web page, that when pressed calls the doPost method. What i would like to know is how i would do this from the arduino?
I tried
client.println("POST /Project/index.html?acctID=1234567 HTTP/1.0");
as a means to call the doPost method and pass it an "acctID", this however doesn't call that doPost method. I don't have a very good understanding of how to send get/post from ethernetclient in arduino (i imagine it doesn't work quite how i'm thinking it does), so hopefully someone can help me understand, thanks!
In response to comment:
So i've continued to play with this and what i've done at this point is I've made a server on my java side that sends data (via sockets) to an arduino server that i've made. What i'm trying to do now is send a simple, small piece of data back to my java program/servlet. What i've tried so far that is the code posted above on the arduino side, and on the java side i've got a simple server:
private static void listenForArduino() throws IOException, ClassNotFoundException {
//static ServerSocket variable
ServerSocket server;
//socket server port on which it will listen
int port = 9876;
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request...");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
I never receive a response, it stalls on this line
server = new ServerSocket(port);
My arduino code (that pertains to this):
if (client.connect(ip, 9876)) {
Serial.println("connected");
client.println("POST /NFCPaymentProject/index.html?acctID=1234567 HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}

Related

How to listen to one client at a time in Java using server socket?

import java.io.*;
import java.net.*;
class MultiServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSock=new ServerSocket(3000);
//server socket creation
System.out.println("waiting for client.........");
Socket socket=serverSock.accept();
System.out.println("client connected ");
BufferedReader keyRead=new BufferedReader(new
inputStreamReader(System.in));
OutputStream ostream=socket.getOutputStream();//sending to client
PrintWriter pw=new PrintWriter(ostream,true);
InputStream istream=socket.getInputStream();//receiving from server (istream object)
BufferedReader receiveRead=new BufferedReader(new
InputStreamReader(istream));
String receiveMessage,sendMessage;
while(true)
{
if((receiveMessage=receiveRead.readLine())!= null)
{
System.out.println("client:>"+ receiveMessage);
}
sendMessage=keyRead.readLine();
pw.println(sendMessage);
System.out.flush();//flush the Stream
if(sendMessage.equals("bye"))
{
break;
}
}
}
}
This code is to connect a client at a time, but I want to display a message saying that the server is busy if other client attempts to chat with the same server. That message should respond on both sides.
i want to display a message that the server is busy if other client attempts to chat with the same server. that message should respond on both the side
Basically impossible. The listen() backlog queue will cause a subsequent client's connection attempt to complete and be queued for the next accept() call by the server. There is nothing you can do about this short of closing the listening socket until you're ready to accept the next client, which introduces all kinds of timing constraints.
You could set a flag while you have a client and check it when you accept another one, and send him the message and disconnect him, but I fail to see the point.
that message should respond on both sides
What both sides? The side of the new client and who else?
Strange requirement. How can a chat server only want one client? Who is he chatting to?

How to keep Socket Connection until Server Process it?

I am writing Socket program , Here Client Sends a String through Stream , Server Process it and writes back to Client. My problem is, after Server process the String , it Writes back to Stream but in client It can't able to read the Stream its showing exception as Exception in while: java.net.SocketException: socket closed Here is my code,
Client ,
public void run() {
while (true) {
try {
// Open your connection to a server, at port 1231
s1 = new Socket("localhost", 1231);
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
InputStream in=s1.getInputStream();
DataInputStream dis=new DataInputStream(in);
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
dos.close();
System.out.println(dis.readUTF());//it is the String from Server after processing
dis.close();
} catch (IOException ex) {
// Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Exception in while: " + ex);
}
}
In Server
public void run()
{
while(true){
try {
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
String clientData=dis.readUTF();
//processing task String
dos.writeUTF("Bus Registered Successfully");
dos.flush();
}
}
Here I am not able to read Bus Registered Successfully at client side . How to Solve this.?
Well there are many things not right in your program. But first let me answer your question ... you are closing the socket just after writing the stream ... so server throws exception, just remove dos.close(); just after the dos.flush();. It will run fine.
Now back to the programming practices ...
1) Server should accept the connection in a while(true) loop and then make a new thread. So following statement should not be the part of run method.
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
2) There is no need of run method in client. Because Every new client will be a new program that has its own variables and socket.
A quick look shows me that the reason the socket is closed is because you used dos.close().
Closing a DataInputStream (or PrintStream, or any similiar stream) will close the underlying socket.
Just take out dos.close().
You can also move the dos.close() to the very end of the try block. As a general rule, don't close anything related to the socket until you're done with the socket.

EOF Exception in a thread using sockets

I have the code below:
while (true)
{
lengthInput = instr.readByte();
// Other code
}
The thing is that I'm using a client to send information to the socket, but after it finishes I got EOF Exception and it brokes the thread, what I need is to manages this and dont stop the thread, because I need to send more information and be able to read it.
Thanks in advance for your help.
I guess the problem is related to your socket initialization. You probably need to check if your client socket indeed successfully create a socket and bind to a specified port. You may also check your client really send data to the outstream and flush to the server side. I have a small project on Android emulators with socket communication. Both my client and serve extends from Java Thread class. Maybe you can gain some idea seeing my code below.
The client side
try {
socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(remote_port));//note we must keep the addr#10.0.2.2
// write out
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(out_msg);
out.flush();
// read in
in = new ObjectInputStream(socket.getInputStream());
socket.setSoTimeout(1000);
in_msg.set_message((Message)in.readObject());
// close all
out.close();
in.close();
socket.close();
return true;
}catch(InterruptedIOException E){}
The server side
while (true) {
try {
// read in message
Socket ClientSocket = serverSocket.accept();
Message out_msg = new Message();
// read in message
ObjectInputStream in = new ObjectInputStream(ClientSocket.getInputStream());
Message in_msg = (Message) in.readObject();
//Log.d(TAG, "recv" + " content:" + in_msg.msg2Str());
message_process(in_msg, out_msg);
// write out message
ObjectOutputStream out = new ObjectOutputStream(ClientSocket.getOutputStream());
out.writeObject(out_msg);
out.flush();
} catch(Exception E){}
}

How to make a SSL tcp server with java?

i'm trying to find out how to create a TCP server with SSL in java. But i don't get what i really need. Do i have to import key-files into java, and i so, how to do this? Or do i just need to change the type of the socket from Socket to SSLSocket? I've read some articles but couldn't find anything helpful because all of them just take http for communicating. I would need it for my own protocol. In my case it would be to have a program like this:
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
In in = new In (clientSocket);
Out out = new Out(clientSocket);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
out.close();
in.close();
clientSocket.close();
}
to use a SSL connection. So how to do this?
Thanks,
Thomas
I found this with a quick Google search.
Here.

Java client/server issue sending objects over sockets [duplicate]

This question already has answers here:
Java socket/serialization, object won't update
(2 answers)
Closed 7 years ago.
I'm creating a standard multi-client/server program in Java. The server accepts connections and spawns a new thread to handle each one. The client also spawns a thread to wait for messages from the server. The client and server communicate by passing Message objects through ObjectInputStream and ObjectOutputStreams.
The initial handshake works fine. When the client starts, it opens a socket connection to the server. The server accepts the socket, sends a Message to the client that the connection was successful. Then the client sends its username back, and both client and server start waiting for messages.
Then I send some text from my client which creates a chat message, and sends it successfully to the server. The server receives this message, and attempts to send it out to all connected clients, which it does (there's only one). The problem is that this message never gets back to the client.
// This is Message.send
public void send(ObjectOutputStream stream) throws IOException{
stream.writeObject(this);
}
// ClientThread.run
public void run(){
try {
out = client.getOutputStream();
out.flush();
ObjectInputStream in = client.getInputStream();
Message msg = null;
int len;
byte[] bytes = null;
int i = 0;
// Continuously read new Messages from the server
while(true){
msg = (Message)in.readObject();
processInput(msg);
}
} catch (Exception e) {
Util.showError(e.getMessage(), "Connection Error");
}
System.out.println("Client exited");
}
// ServerThread.run
public void run() {
try {
out = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
Message msg = null;
while(client.isConnected()){
msg = (Message)in.readObject();
processInput(msg);
}
in.close();
client.close();
} catch (Exception e) {
server.addMessage(e.getMessage());
}
}
I don't see any calls to flush(), without which the data may never make it from point a to point b.
I'd recommend using the ObjectOutputStream atop a ByteArrayOutputStream, and pushing the resulting byte array across the wire, and then reversing the process on the other end.

Categories

Resources