One-way connection between android tablet, router and 2 devices - java

I've got question, that I haven't found answer for yet. I have 2 devices with wifi each, that are sending special data. I want to show this data at the same moment on a tablet. There is a router with network, both tablet and that devices are connected to this network.
How to solve this? Should I use serversocket? I don't know if I explained it clear enought, if not, please ask. Thanks for any response.

I have the same application running on the company I work.
The "device" is a micro-controller based device that is implemented the lwIP (lightweight IP protocol) and it's listening to the port 83 and every 500ms the tablet goes and read new fresh data and plot it in a graph. Works like a charm.
(in case you'll be plotting charts, I used the AChartEngine and you can check on my profile a question/answer on it with some useful info)
the code below is a simplified version of what I'm doing. The complete version includes SEVERAL try{ } catch() { } in case it catches an exception it try closing the socket and return null;
public static String SendMessage(String message, String ip, int port) {
// Connect to host ==================================
Socket socket = new Socket();
socket.setSoTimeout(TIMEOUT);
InetSocketAddress addr = new InetSocketAddress(ip, port);
socket.connect(addr, TIMEOUT);
// Send Message ======================================
byte[] outputBuffer = message.getBytes();
socket.getOutputStream().write(outputBuffer);
// Zero the input buffer =============================
for (int i = 0; i < inputBuffer.length; i++) {
inputBuffer[i] = 0;
}
// Read the response ==================================
int count = 0;
do {
count = socket.getInputStream().read(inputBuffer);
} while (count != -1);
// Close connection ====================================
close(socket);
// Return message ======================================
return new String(inputBuffer).trim();
}
hope it helps,
happy coding.

1. Socket will be a good idea.
For Sending :
Socket s = new Socket();
s.connect(new InetSocketAddress("IP_ADDR",PORT_NO);
OutputStream o = s.getOutputStream();
PrintWriter pw = new PrintWriter(o);
pw.write(msg); // msg will be the data needed to send
For Receiving:
Socket s = new Socket();
s.connect(new InetSocketAddress("IP_ADDR",PORT_NO);
InputStream i = s.getInputStream();
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = new String();
while((str=br.readLine())!=null){
System.out.println(str); // do whatever u want to do with str, the data read
}

Related

Android socket is connected but doesn't send data

I'm developing an Android client app which talks to server via a plain TCP Socket, let's assume that the server ip 192.168.1.2 and the androdi device ip is 192.168.1.3.
I open the socket, i check if socket is connected (i get true as result) and after that i write a presentation message.
Here is my code
// scoket setup
Sockets = new Socket(addressToConnect, 2015);
s.setSoTimeout(2500);
setTcpNoDelay(true);
// if i'm connected
if (s.isConnected()) {
// wrapping streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// sending data
String presentationMessage = "Presentation message content--- TERM";
dos.write(presentationMessage.getBytes("UTF-8");
dos.flush();
// buffers
byte[] readBuffer = new byte[4096];
StringBuffer responseBuffer = new StringBuffer();
// read data until command terminator string is found
boolean readResponse = true;
while (readResponse) {
int dataBufferLength = dis.read(readBuffer);
String chunk = new String(readBuffer, 0, dataBufferLength, "UTF-8"));
responseBuffer.append(chunk);
readResponse = ! chunk.endWith("--- TERM");
}
// Process data here
} else {
// Notify missing connection here
}
// here i close the socket
When i execute this code the execution seems working like a charme until the first read which timesout.
Sniffing the used WIFI network with a third machine i can't see the connection establishment and the written stream even if the code doesn't throw any exception before the read timeout.
I granted the android.permission.INTERNET in manifest.
Are there some other permissions to grant? or what i'm doing wrong?
Executing the same code in a standard Java SE environment everything goes fine.
I'm testing the code on a Nexus 5, Nexus 9 and Samsung S3 and S4 and the project is compatible with API 14+
Edit: Fixed typo in code example
You are reading from dos and writing to dis. You should reverse that.

Java Message sent from client to server

I'm using a socket to connect my client with the server, I need a way so that when somebody tries to login on the client with an account, it sends the username and password to the server, and checks if the account exists. I just need to know how to make it send the message to the server when they press login.
i tried this to make it send a message to the server
public static void sendmsg(String a, String b)
{
try
{
String host = "127.0.0.1";
int port = 43655;
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);
String sendMessage = a;
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
nice you are working with Sockets, well I have an approach you can try, and maybe if it is useful you can consider for your implementation.
First of all I will create an entity to handle those values and fill it with the incoming data.
class UserAuth {
private String username;
private String password;
//Consider here your getters and setters, I am not including them
}
I will use the entity as the parameter for the method while sending and maybe you can fill it as something like:
UserAuth attemptingUser = new UserAuth(...)
ObjectInputStream works fine for these kind of scenarios. If you still want to work with Strings, you can use BufferedReader and try to merge your username and password as one single String and use the .readLine() method to obtain (separated with commas), then use String methods such Split but I find that could take some more time, should be better if you handle it with an object. But it depends on the complexity you want to add to your application :).
class AuthClient {
public void sendMsg(UserAuth attemptingUser) {
String host = "localhost";
int port = 2055;
//1. Create the socket
Socket sender = new Socket(host, port);
//2. Create an object output stream to write the object into the stream
ObjectOutputStream outputWriter = new ObjectOutputStream(sender.getOutputStream());
//3. Write (send the object)
outputWriter.writeObject(attemptingUser);
//4. Close
outputWriter.close();
sender.close();
}
}
class AuthServer {
ServerSocket ss = new ServerSocket(2055);
public void receiveMsg() {
//1. Accept the connection
Socket conn = ss.accept();
//2. Receive the flow
ObjectInputStream readStream = new ObjectInputStream(conn.getInputStream());
//3. Read the object
UserAuth userReceived = readStream.readObject();
//4. Verify against file, db or whatever
if (userReceived.getUsername().equals("admin") && userReceived.getPassword().equals("admin")) {
//Authentication
}
}
}
(This is added as the part I edit for what you asked me in the comments)
public void sendMsg(String username, String password) {
String host = "localhost";
int port = 2055;
//1. Create the socket
Socket sender = new Socket(host, port);
//2. Create the UserAuth object based on the parameters you received
UserAuth myuser = new UserAuth();
myuser.setUsername(username);
myuser.setPassword(password);
//3. Follow same instructions for the creation of ObjectOutputStream...
ObjectOutputStream objectWriter = new ObjectOutputStream(sender.getOutputStream());
objectWriter.writeObject(myuser);
//That is what I would use if I keep your structure
}
If you want to keep your structure using Strings, I would simplify and reduce impact of I/O by using the String methods. Since you know you are always expecting user/password, I would merge your two params in one single String or use special char and on server side handle with StringTokenizer class. Or maybe handle with the "split" method. You have many options here.
So far, this will be my approach for the problem you are facing. Hope it helps somehow. Best regards and happy coding :).
What you have done looks OK to me but it all depends on what the server is expecting to receive. What is the terminating character as you have not sent one unless it's already contained within your String a variable.
If the server is expecting an end of line character (which you don't currently send) you can use a PrintWriter instead of a BufferedWriter like this
pw = new PrintWriter(socket.getOutputStream(), true);
pw.println(a);
Your server would then be doing something like this
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String value = br.readLine();

Keep client to server connection open and close on request

I have a TCP client application in Java, through this application i can communicate with a server application.
I have a simple method sendCommand which sends the message to the server:
void sendCommand(String command) throws IOException {
String ipaddress = "192.168.0.2";
Socket commandSocket = null;
PrintWriter out = null;
BufferedWriter out = null;
BufferedReader in = null;
BufferedWriter outToDetailFile = null;
FileWriter fstream = null;
String version = "";
int numberOfBallsInGame;
int ledCycleState = 1;
commandSocket = new Socket(ipaddress, 7420);
out = new BufferedWriter(new OutputStreamWriter(commandSocket.getOutputStream()));
in = new BufferedReader(new InputStreamReader(commandSocket.getInputStream()));
out.write("c");out.flush();
out.write(command);out.flush();
String message = in.readLine();
//System.out.println(message);
out.close();
in.close();
commandSocket.close();
}
Now, because the server application is on the machine which does not accept more than 2 connections in 20 seconds i need to modify my method and "split" it in 3 different methods (i think).
My plan is the following:
I would like to call the connection to the server in one thread, keep it opened untill i want to close it, but i should be able to send the commands between opening the connection and closing it.
I'm pretty new to Java and i'll try to explain here exactly what i want to do:
1) I want to open the connection to TCP server.
2) After opening the connection i want to be able to send commands to an already opened connection by calling this method:
void sendCommand(String command) throws IOException {
out.write("c");out.flush();
out.write(command);out.flush();
}
And after i'm finished with sending commands i want to call some method to close my running connection.
Because i'm pretty new to java it would be very nice if someone could show me how to achieve this or modify my method.
Thank you in advance,

(Client - Server) Java control when Server's serversocket accepts client(s) is not working [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently learning about Sockets and my homework is to create a chat room where multiple clients can talk freely. The hint given by the teacher was that the chat room server only accepts the client when the client attempts to send a message. This homework is supposed to be done without using threads.
Following the hint given, I tried to create unbound ServerSocket and Socket in both the client and the server code. The key idea is that when the client attemps to send a message to the server, the client code would connect the unbound Socket, which will then trigger the server to connect the unbound ServerSocket and to accept the client.
However, when I run the code, both the server and client code are running, and they claim that all the connections are made, but I could not transmit messages between the client and the server at all.
I have tried finding answers online, but I could not find any. I would like to ask if my way of deciding when the server accepts the client is correct.
my ChatRoom Server:
public class ChatRoom {
public static void main(String[] args) throws Exception {
int portNum = 4321;
ServerSocket serverSocket = new ServerSocket();
int count = 1;
while (true) {
// redeclare everything each round
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
String inputLine = null;
// accept each time round
serverSocket.bind(new InetSocketAddress(portNum));
socket = serverSocket.accept();
System.out.println("newly accepted!");
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
if (!((inputLine = in.readLine()).equals("Bye"))) {
System.out.println("Client says: " + inputLine);
out.println(stdIn.readLine());
out.flush();
System.out.println("Message Count: " + count);
count++;
}
else {
out.println(inputLine);
serverSocket.close();
socket.close();
out.close();
in.close();
}
}
}
}
my ChatRoomClient:
public class ChatRoomClient {
public static void main(String[] args) throws Exception {
String hostName = "localhost";
int portNumber = 4321;
Socket echoSocket = new Socket(); // creates an unbound socket
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
String userInput;
do {
out = null;
in = null;
stdIn = null;
// each time round the unbound socket attempts to connect to send a message
echoSocket.connect(new InetSocketAddress(hostName, portNumber));
System.out.println("successfully connected");
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
userInput = stdIn.readLine();
out.flush();
System.out.println("Server says: " + in.readLine());
}
while (!userInput.equals("Bye"));
// close everything
echoSocket.close();
in.close();
stdIn.close();
}
}
Thanks!
The hint given by the teacher was that the chat room server only accepts the client when the client attempts to send a message. This homework is supposed to be done without using threads.
The hint given by the teacher doesn't make sense. The client has to connect, then the server accepts. The client can't send a message without connecting first. Maybe the teacher really means that the client shouldn't connect until he has something to send?
Following the hint given, I tried to create unbound ServerSocket and Socket in both the client and the server code. The key idea is that when the client attemps to send a message to the server, the client code would connect the unbound Socket, which will then trigger the server to connect the unbound ServerSocket and to accept the client.
But that won't happen. It's impossible. If you try to connect to a port that isn't listening, you will get a ConnectException. The only way to put the port into listening state is to bind the ServerSocket. There is no magical back-door by which the server can possibly know that the client wants to connect so it should now do the bind.
This homework is supposed to be done without using threads.
Impossible to 'create a chat room where multiple clients can talk freely' that way, unless you are expected to use non-blocking I/O, or abuse the available() facility, or use a connection per message, but then I don't see how you can communicate one client's messages to the other clients, unless you're allowed to batch them up.
There are too many imponderable aspects of this assignment as you have described it. The question as posed doesn't actully make sense, and your proposed solution certainly doesn't. You should just go ahead and write your program the normal way, with a connect, an accept, and some I/O. Get it working while your teacher comes up with a clarification.
Ah... With out using thread for the server you will not be able to serve multiple clients. Anyway, your current codes have issues and your logic are not correct.
Your stdIn should be declare and instantiated outside of the loop, you don't need to keep on creating the stdIn object for each loop.
Your "in" socket accept() and echoSocket.connect() should also be outside of the loop, this is why you are not getting any answer from the server because you are not listening on the same line. It's like your phone, keep on FLASH to dial the new number each time. all point to the same server, but it is different connection.
So, the idea is to establish a connection between server and client (single connection) that can communicate both way (via input and output stream). Then you can loop and talk start with the client, then server receive, then server talk, then client receive then client talk.... until client say Bye...
for more: http://ta.cnci.org/basicirc
thought I would like to update, I managed to solve my problem without using threads. Just sockets haha. Thought it would be good to post my answer for reference..
my ChatRoom Server:
public class ChatRoomServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(4321);
while(true) {
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader
(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = in.readLine();
System.out.println("Client says: " + inputLine);
in.close();
clientSocket.close();
}
}
}
my ChatRoom Client:
public class ChatRoomClient {
public static void main(String[] args) throws Exception {
String hostName = "localhost";
int portNum = 4321;
BufferedReader stdIn = new BufferedReader
(new InputStreamReader(System.in));
while (true) {
String userInput;
userInput = stdIn.readLine();
Socket echoSocket = new Socket(hostName, portNum);
PrintWriter out = new PrintWriter
(echoSocket.getOutputStream(), true);
out.println(userInput);
out.flush();
out.close();
echoSocket.close();
if (userInput.equals("Bye")) {
stdIn.close();
break;
}
}
}
}

Java read timeout doesnt work

I try to connect with my server by using socket on android. I want it to work like this; when i send a request to the server, if there is a response, call my response function. If the timeout of 500 ms happens (will check the exception and the boolean i set), i want to execute another function. But with this code im using, when i send something to the server and wait for response, it executes the onServerResponse function if there is a response and doesnt do anything(hangs) when there is not a response. How can i edit this code so it will throw a timeout exception when there is no response?
boolean control = false;
try{
Socket socket = new Socket();
socket.setSoTimeout(500);
socket.connect(new InetSocketAddress(InetAddress.getByName(SERVER_IP),SERVER_PORT));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
bw.write("asdasd\n");
bw.flush();
control = true;
int readInt = -1;
String read = null;
StringBuilder sb = new StringBuilder("");
while((readInt = socket.getInputStream().read()) != -1){
sb.append((char)readInt);
}
read = sb.toString();
if(read != null && read.trim().length() > 0){ onServerResponse(read); }
}catch(Exception e){ Log.v("Main", "GOT AN ERROR: "+e+control); }
Problem solved, see the comments for answer.
I'm not sure if this answers your question, but setSoTimeout only applies to reads on the socket after it is connected, not to establishing the connection itself. For that, use the socket.connect(SocketAddress address, int timout) overload.) overload. You probably want to use both.
Something like this would work:
Socket socket = new Socket();
InetAddress addr = InetAddress.getByName(SERVER_IP);
SocketAddress sockaddr = new InetSocketAddress(addr, SERVER_PORT);
// 500ms is too short, up to you.
// normal time would be 5 to 20 seconds, depends on network (intranet/internet)
socket.connect(sockaddr, 500);
// 500ms to timeout reading from the socket
socket.setSoTimeout(500);

Categories