i want to make communication between android device and java server.
Server side:
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
OutputStream out = socket.getOutputStream();
PrintStream pw = new PrintStream(out);
pw.print("hello");
pw.flush();
socket.close();
Android client side :
public class connectTask extends Thread {
#Override
public void run() {
super.run();
while (true) {
try {
Socket socket = new Socket("192.168.0.101", 4444);
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(line);
}
});
socket.close();
} catch (IOException e) {
}}}}
and starting thread this way:
thread = new Thread(new connectTask());
thread.start();
the problem is I cannot get anything from java server. I either send or receive data wrong and i can't figure out what's the issue, what am I doing wrong here?
Your code looks good (may be String line = ... should be final String line = ...) and IP address and port of Server need to be checked.
Related
I'm able to send string to the server and server also received the same. Server is able to send the acknowledgment but client is not getting acknowledged until server ends the connection. But I don't want to close the connection. How should I display the acknowledgment without closing the connection?
//This is Client
public void Actuator1_Stop(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Socket socket = new Socket("localhost", 1028);
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF("Stop_Actuator");
dout.flush();
System.out.println("Command Sent = Stop_Actuator");
//Get the return message from server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("ACK received from the server : " +message);
socket.close();
} catch(Exception exception) {
exception.printStackTrace();
}
}
//This is Server
class Socket4 implements Runnable {
public void run() {
try {
ServerSocket ss = new ServerSocket(1028);
while(true) {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String cmd = dis.readUTF();
System.out.println("Command= "+cmd);
//Sending the response back to the client
String ack = null;
OutputStream os = s.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
if(cmd.equals("Stop_Actuator")) {
ack= "Ok";
bw.write(ack);
} else {
ack = "Error";
bw.write(ack);
}
System.out.println("ACK sent to the client is "+ack);
bw.flush();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
public class MyServer {
public static void main(String[] args) {
Socket1 s1 = new Socket1();
Socket2 s2 = new Socket2();
Socket3 s3 = new Socket3();
Socket4 s4 = new Socket4();
Thread t1 = new Thread(s1);
Thread t2 = new Thread(s2);
Thread t3 = new Thread(s3);
Thread t4 = new Thread(s4);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
}
How should I display the acknowledgment without closing the connection?
In your client you are doing a read-line:
String message = br.readLine();
However from the server you are not sending a complete line. You need to add line termination characters to the end of the message:
ack = "Ok\n";
bw.write(ack);
The read-line then completes and the client gets the ack. Obviously the error ack also needs a newline ("Error\n").
Make sure that you are properly closing the accepted socket and the server socket that are created in Socket4.run(). I assume that you are just posting portions of your code but make sure to close those sockets in a try/finally blocks.
I'm having the following TCP client code:
public static void register(InetAddress ip, int port, String name) {
try {
Socket clientSocket = new Socket(ip, port);
send("reg:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send(String str) {
try {
String sentence = str;
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(sentence);
} catch (IOException e) {
Log.e("CONNECT", e.getMessage());
}
}
They both are called in onClicks and i know that for sure.
I also have the following Server code:
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9876);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
outToClient.writeBytes("msg: Hello! kalin pedro");
}
}
When trying to send data to the server i don't get an exception, i also know that I'm connected to it because the application is crashing when i terminate the server application. The problem is that the server doesn't receive anything until i terminate the client application. Everything that i have tried to send until that moment is all received from the server at once. I looked at the network activity tab provided by Android Studio and there is a change when sending data, the server just doesn't receive it(or at least i don't see it receive it) until i terminate the client application.
I have a client and a server. The client binds a socket on a specific port, the server sends back a new port to the client and the client should bind a new socket on the new port number.
From the main server thread, I start a thread that sends a message to the client once the server is ready and is listening to the new port, so that the client can attempt to connect to the new port. The pipe from the child thread is not sending the message to the client.
So both client and server just freeze, it seems like a deadlock, but im not sure. This line of code in the client: System.out.println("FROM SERVER: " + inMsg_rport); is not executing.
Server Code:
class server
{
public static void main(String argv[]) throws Exception
{
String newPort;
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(5555);
clientSocket = serverSocket.accept();
DataOutputStream serverOut =
new DataOutputStream(clientSocket.getOutputStream());
int r_port = 5556;
Thread appThread = new Thread(new serverApp(serverOut, r_port));
appThread.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
static class serverApp implements Runnable
{
DataOutputStream serverOut;
int nPort;
public serverApp(DataOutputStream servO, int r_port)
{
this.serverOut = servO;
this.nPort = r_port;
}
#Override
public void run()
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(nPort);
serverOut.writeBytes(sr_port);
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
}
Client code:
class client {
public static void main(String argv[]) throws Exception
{
String serverIp = argv[0];
String msg = argv[2];
int port = Integer.parseInt(argv[1]);
Socket clientSocket = new Socket(InetAddress.getByName(serverIp), port);
BufferedReader clientIn =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inMsg_rport = clientIn.readLine();
System.out.println("FROM SERVER: " + inMsg_rport);
int r_port = Integer.parseInt(inMsg_rport);
clientSocket.close();
System.out.println("Closed connection");
Socket new_clientSocket = new Socket(InetAddress.getByName(serverIp), r_port);
}
}
readLine() in your client is a blocking call, waiting for an end-of-line character
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
You aren't sending an end of line character. You're using a DataOutputStream in your server and sending raw bytes.
Don't use a DataOutputStream in your server; I don't think that's really what you're looking for. Just send the port number as text with an end of line character and be done with it.
I have a relatively simple program where I try establish Client Server connection and at the same time I use threads in the client side to allow for multiple connections.
I run the server and then the server invokes the client constructor and passes the port connection to the client and the thread is started on the client side.
The problem I have is that when I run the server side it doesn't want to go beyond the constructor call. It seems to get stuck at the constructor.
Sorry all this sounds a bit confusing
Any thoughts perhaps
this is the server side
ServerMultipleThreads()
{
System.out.println("Starting the server first...");
try
{
ServerSoc = new ServerSocket(7777);
listening = true;
}
catch(Exception e)
{
System.out.println(e.toString());
System.exit(1);
}
System.out.println("The server has started running");
while(listening)
{
try
{
//creating the client socket and starting the new client session
new ClientSession(ServerSoc.accept());
System.out.println("The clientSession was called");
in = new DataInputStream(clientSocket.getInputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(in));
os = new PrintStream(clientSocket.getOutputStream());
while(true)
{
line = is.readLine();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myFile,txt")), true);
out.println(line);
}
}
catch(IOException ioe)
{
System.out.println(ioe.toString());
}
}
}
and this is on client side
ClientSession(Socket s)
{
clientSocket = s;
try
{
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out.println("Welcome");
}
catch(IOException exe)
{
System.out.println(exe.toString());
}
//starting the thread
while(runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void run()
{
while(runner == Thread.currentThread())
{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String stdIn;
try
{
while((stdIn = buf.readLine()) != null)
{
out.println(stdIn);
}
}
catch(IOException exe)
{
exe.toString();
}
try
{
Thread.sleep(10);
}
catch(InterruptedException e){}
}
Kind regards
Arian
That is because ServerSocket.accept() blocks until it receives a client request.
You need to have a client calling the server, something like this:
Socket socket = new Socket(host, port);
InputStream in = socket.getInputStream();
// write some data...
I am trying to write a small program, that opens a server, creates a client that connects to this server and receives a message from it.
This is the Code so far
public static void main(String[] args) {
final ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(12345);
Thread t = new Thread(){
public void run(){
try {
Socket server = serverSocket.accept();
PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
writer.write("Hello World");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
Socket client = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = reader.readLine();
System.out.println("Received " + message);
} catch (IOException e1) {
e1.printStackTrace();
}
}
If i run program it keeps waiting in readLine() - so obviously the client does not receive the message from the server.
Has anyone got an idea why this isn' working?
Your reading thread is waiting for a newline in the data stream. Just change the server to use:
writer.write("Hello World\r\n");
and you'll get the result you were expecting. Alternatively, you can just close the server socket, and then readLine will return when it reaches the end of the data stream.
You should put the readline in a loop as follows:
public static void main(String[] args) {
final ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(12345);
Thread t = new Thread() {
public void run() {
try {
Socket server = serverSocket.accept();
PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
writer.write("Hello World");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
Socket client = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
// Check this --------------------------------------------------->
String message = null;
while ((message = in.readLine()) != null) {
System.out.println("Received " + message);
break; //This break will exit the loop when the first message is sent by the server
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
You can read this documentation for further explanation: http://download.oracle.com/javase/tutorial/networking/sockets/