I am currently starting a Thread on my device to communicate with my server.
The problem is that the code statement after the socket init is never called:
#Override
public void run(){
try{
socket = new Socket(context.getString(R.string.host), context.getResources().getInteger(R.integer.port));
Log.d("AppTest", "ActivityStart");
out = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
if(socket != null){
if(awaitingString != null){
out.println(awaitingString);
out.flush();
awaitingString = null;//Reset awaiting string
}
String line;
while((line = reader.readLine()) != null){
if(line != null){
answer = line;//Overwrite answer
}
}
}else{
socket = new Socket(context.getString(R.string.host), R.integer.port);
out = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
}
}catch(Exception e){
e.printStackTrace();
}
}
In the debug I should be able to AppTest: ActivityStart, but it's not showing up.
PS: I am using the IPv4 address of my computer as host
Related
I'm using a method called registerDevice() in my android app
code to send and receive specific data which contains multiple lines. But I keep getting this error:
W/System.err: java.net.SocketException: Connection reset
public void registerDevice(){
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Socket s = new Socket(gateway, 1234);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output.println("hello world\r\n");
output.flush();
StringBuffer stringBuffer = new StringBuffer("");
String line = null;
while ((line = input.readLine()) != null) {
stringBuffer.append(line);
}
final String st = line.substring(5);
handler.post(new Runnable() {
#Override
public void run() {
if (st.trim().length() != 0)
Toast.makeText(getApplicationContext(),st,Toast.LENGTH_LONG).show();
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
UPDATE: I changed the code to this:
Socket s = new Socket(gateway, 1234);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output.println("hello world\r\n");
output.flush();
final String st = input.readLine();
handler.post(new Runnable() {
#Override
public void run() {
if (st.trim().length() != 0)
Toast.makeText(getApplicationContext(),"st",Toast.LENGTH_LONG).show();
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm Still getting exceptions on the "final String st = input.readLine();" line. I am supposed to get a MAC address from the server and then the server closes the connection.I checked the server and there is nothing wrong with it, it closes the connection AFTER it sends me the MAC.
Guys I found the problem, it was the packet I was sending, I just changed outout.println() to output.write(), so now the server recognized my command and sent the data I needed which led to my input stream not being empty and avoiding exceptions.
I'm trying to add a client socket in the file ViewRootImpl.java. I'm creating the socket in a new thread with an handler because I need to comunicate between threads. I'm sending a message to Vthread every time performTraversal is called.
Client code in ViewRootImpl.java:
public class Vthread extends Thread{
Viewhandler mViewhandler;
Handler mhandler;
Socket client;
BufferedReader in;
PrintWriter out;
String s;
String line;
Vthread(Viewhandler handler){
mViewhandler = handler;
in = null;
out = null;
s = "hello";
client = null;
}
#Override
public void run(){
Looper.prepare();
try{
client = new Socket("10.0.2.2", 60000);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
mhandler = new Handler(){
#Override
public void handleMessage(Message msg) {
try{
if(out != null && in != null && client != null){
out.println(s);
out.flush();
line = in.readLine();
}
}catch (IOException e) {
e.printStackTrace();
}
}};
Looper.loop();
}
}
The server code in the host:
Socket socket;
ServerSocket server;
SocketAddress sockaddr;
BufferedReader in = null;
PrintWriter out = null;
String line;
String s = "bye";
server = null;
try{
sockaddr = new InetSocketAddress("127.0.0.1", 60000);
server = new ServerSocket();
server.bind(sockaddr);
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}catch (IOException e) {
e.printStackTrace();
}
try{
System.out.println("connected");
while(!Thread.currentThread().isInterrupted()){
line = in.readLine();
System.out.println(line);
out.println(s);
}
if (server != null ) server.close();
}catch (IOException e) {
e.printStackTrace();
}
The connection is accepted but the server doesn't receive any message from client. A problem that I identified is that more than one process might be using the socket. So I used a file in the internal storage of my application to restric the socket to my application only, but the problem remains. Code to restrict the socket to my application:
if(mVthread.mhandler != null) {
try{
if(reader == null) reader = new BufferedReader(new FileReader(file));
Message msg = Message.obtain();
msg.arg1 = 1000;
mVthread.mhandler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
EDIT
The problem is that the client socket sends a message but the server doesn't receive it. Both sides are blocked in the receive function. Any idea on what I am doing wrong?
I am executing shell commands from my Android APP. I am able to execute the command but unable to read the response from Server.
My code is as follows :
public String executeThroughSocket(int portNo, String portAddress, String command) throws IOException {
StringBuilder responseString = new StringBuilder();
PrintWriter writer = null;
BufferedReader bufferedReader = null;
Socket clientSocket = null;
try {
clientSocket = new Socket(portAddress, portNo);
if (!clientSocket.isConnected())
throw new SocketException("Could not connect to Socket");
clientSocket.setKeepAlive(true);
writer = new PrintWriter(clientSocket.getOutputStream(), true);
writer.println(command);
writer.flush();
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String str;
while ((str = bufferedReader.readLine()) != null) {
responseString.append(str);
}
} finally {
if (writer != null)
writer.close();
if (bufferedReader != null)
bufferedReader.close();
if (clientSocket != null)
clientSocket.close();
}
return responseString.toString();
}
There is nothing wrong with my code. It was the server that was not sending any response.
You have to set timeout for socket
clientSocket .setSoTimeout(5000); // milisekundy
I have 2 programs: a client and a server.
The server creates a ServerSocket and the client connects using:
address = InetAddress.getByName(host);
conn = new Socket(address, port);
this works, but here is the problem: void mousePressed() { gets called once the mouse is clicked, executing this: (client side)
void mousePressed() {
try {
BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write("123");
osw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
the server should receive the input using:
BufferedReader reader = new BufferedReader(
new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
StringBuilder result = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
result.append(line);
}
reader.close();
println(result.toString());
The server only receives the input after the socket has been closed with: conn.close(); on the client side or quitting the client. As i want to be able to click the mouse multiple times, i can't close the socket.
What can i do to send input without closing the socket?
Edit: connection code:
Server:
// init
ServerSocket socket1;
int main_port = 5204;
// in main
try {
socket1 = new ServerSocket(main_port);
Socket conn = socket1.accept();
} catch (Exception e) {
e.printStackTrace();
}
Client:
// init
String host = "localhost";
int port = 5204;
Socket conn;
InetAddress address;
// in main
try {
address = InetAddress.getByName(host);
conn = new Socket(address, port);
} catch (Exception e) {
e.printStackTrace();
}
My solution (based on other answers and comments):
1) Changing osw.write("123"); to osw.write("123\n"); in the client.
2) Replacing
BufferedReader reader = new BufferedReader(new InputStreamReader(new
BufferedInputStream(thread_cnn.getInputStream())));
StringBuilder result = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
result.append(line);
}
println(result);
reader.close();
with
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
String result = reader.readLine().toString();
println(result);
reader = null;
result = null;
on the server.
You are writing an incomplete line, and trying to read complete lines. Terminate the text you send with a line break so it can be read when it arrives.
Also, do not catch and ignore exceptions. If something goes wrong you will want to know about it.
try {
BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write("123\n");
osw.flush();
} catch (Exception e) {
e.printStackTrace();
}
I would like to create a Java server socket application that receives a TCP packet and reads the content of it. Based on the contents of the packet it will perform several actions. I managed to get to the point where it reads some content and prints a string System.out.println(sb.toString());
But (a) not all the content is printed and (b) I am not sure how to process the content as they arrive in network order. An example would be to receive an HTTP packet and from the header to report the "Content-Length" or the "User-Agent". Any example would be appreciated.
public static void main(String[ ] args){
PrintWriter out = null;
BufferedReader in = null;
int bufferSize = 0;
try{
String message = args[0];
int count = 0;
ServerSocket connectionSocket = null;
try {
connectionSocket = new ServerSocket(4444);
System.out.println("Server started");
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
while(true){
count++;
clientSocket = connectionSocket.accept();
System.out.println("TCP packet received… " + count);
InputStream is = clientSocket.getInputStream();
out = new PrintWriter(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
clientSocket.close();
}
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
}
catch(Exception e){
e.printStackTrace();
}
}