I've been trying to get a basic socket connection working between my server and phone. The following code works on the Android emulator perfectly, but when I try it on my phone, it fails and I have no idea why. I've tried most suggestions I could find on SO and Google and none of them work.
My server code is just some basic Ruby: require 'socket'
server = TCPServer.new 2000
puts 'Server started!'
loop do
Thread.start(server.accept) do |client|
puts "Received client"
client.write "Connection established."
while text = client.gets
puts text
client.puts text # Just echo the result back...
end
client.close
end
end
And my client code is as follows: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
try{
Socket s = new Socket("***", 2000);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("test\r\n");
out.flush();
out.close();
}catch(Exception e){
}
}
The code returns the expected response on the emulator:
Server started!
Received client
test
But when I run it on my phone, it only returns:
Server started!
Received client
Clearly it is establishing the connection. I have some more in-depth code that I wrote, that also writes back to the server, and again, the emulator writes & receives, but my phone does neither, after a while, my phone reports: "Connection closed by peer."
Any ideas would be great!
Edit: it seems to work on my friend's phone... so now I'm even more stumped... I'm using a Sony Xperia
You are never reading any input from your input stream, so it's just waiting.. Maybe what you want to do is call readLine() on your buffered reader. And maybe put your output stream code before the input stream code.
Turns out there is a problem with port 2000 on the carrier MTN. Using another port solved my problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.