I create a simple network-testing application.
But It doesn't work and always throw error at Socket().
I tried to check error message by using getMessage(), there was no message printed.
What should I do?
public static void main(String args[]){
ServerSocket serverSocket = null;
Socket socket = null;
try{
serverSocket = new ServerSocket(14100);
socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] arr = new byte[100];
in.read(arr);
System.out.println(new String(arr));
String str = "Hello Client";
out.write(str.getBytes());
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
try{
socket.close();
}
catch(Exception ignored){}
try{
serverSocket.close();
}
catch(Exception ignored){}
}
}
Below is android code for Client.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
TextView tv = (TextView) findViewById(R.id.id_tv);
Socket socket = null;
try{
socket = new Socket("192.168.0.52",14100);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
String str = "Hello Server";
out.write(str.getBytes());
byte arr[] = new byte[100];
in.read(arr);
tv.setText(new String(arr));
}
catch(UnknownHostException uhe){
}
catch(IOException ioe){
}
catch(Exception e){
}
finally{
try{
socket.close();
}
catch(Exception ignored){
}
}
}
Of course, I added permisson for android in AndroidManifest.xml
Move the socket code out of UI main thread onCreate() to an AsyncTask or a regular thread.
For a quick test, wrap all your socket code into a thread like so:
new Thread() {
public void run() {
// Move your socket code here for a quick test
}
}.start();
Related
I want to create a socket connection between my server and my client. My client should reconnect, after the connection timed out. For this, I try every 3 seconds to connect with my socket. And this works. But then, when I want to start reading, but then I get the error "socket closed". What could be the mistake?
Here is the error log (It's on pastebin, it doesn't formate here right):
http://pastebin.com/2t8zAvcx
But I try to get the IP from the socket before I start reading and this works...
Here is my reconnect method:
public void reconnect(){
new Thread(new Runnable() {
#Override
public void run() {
try{
try{
socket.close();
socket = null;
}catch (IOException e) {
}
socket = new Socket(BackgroundService.HOSTNAME, BackgroundService.PORT);
connected = true;
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(username);
output.flush();
}catch(UnknownHostException e){
connected = false;
}catch(IOException e){
connected = false;
}
}
}).start();
}
Here I wait for an input:
public Notification waitForNotification(){
try{
if(!(connected))return null;
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String input;
Log.e("Before Input", socket.getInetAddress()+"");
while((input = inputStream.readUTF()) != null){
Notification notification = new Notification(input);
return notification;
}
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e("Lost Connection3", "ERROR");
connected = false;
return null;
}
}
And here I manage it:
#Override
protected void onHandleIntent(Intent intent) {
Log.e("HII", "HII");
username = getDataFromStorage.loginData(getApplicationContext())[0];
new Thread(new Runnable() {
#Override
public void run() {
ConnectionService connectionService = new ConnectionService(username);
while (true) {
if(!(connectionService.getConnectionState())){
try {
Thread.sleep(3000);
connectionService.reconnect();
continue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Notification notification = connectionService.waitForNotification();
if(notification == null){
continue;
}
processStartNotification(notification);
}
}
}).start();
}
And here I start the connection:
public ConnectionService(String username){
this.username = username;
try{
socket = new Socket(BackgroundService.HOSTNAME, BackgroundService.PORT);
connected = true;
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(username);
output.flush();
}catch(UnknownHostException e){
connected = false;
}catch(IOException e){
connected = false;
}
}
I am currently working on a project that requires an android app to connect to a java server that I have created. The problem is that the socket does not initialize. I have added the permissions to the AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
My app code looks as follows:
Button Trigger:
View.OnClickListener btnDownloadListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
//Implement download code
try{
new ConnectionManager().execute("10.90.181.91" , "21002");
}catch(Throwable t){
}
}
};
ConnectionManager Background Function:
protected String doInBackground(String... args) {
try{
Log.i("Test", "background thread started");
int port = Integer.parseInt(args[1]);
InetAddress serverAddr = InetAddress.getByName(args[0]);
Socket connSock = new Socket(serverAddr, port);
Log.i("Test", "Created Socket");
}catch(Throwable t){
}
return "";
}
The log is outputting "background Thread Started", but never outputs "Created Socket"
The Server code is as follows:
Main method
try{
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(21002);
} catch (IOException e) {
System.err.println("Could not listen on port: 21002");
}
int count = 0;
while(listeningSocket){
try{
Socket clientSocket = serverSocket.accept();
new ServerThread(clientSocket).start();
}catch(Throwable t){
}
}
System.out.println("You should not be here");
serverSocket.close();
}catch(Throwable t){
}
ServerThread
public class ServerThread extends Thread {
private Socket socket = null;
private String s;
private InputStream in;
private OutputStream out;
BufferedReader is;
BufferedWriter os;
public ServerThread(Socket s) {
socket = s;
System.out.println("Thread started: " + socket.getInetAddress());
try{
in = socket.getInputStream();
out = socket.getOutputStream();
out.flush();
is = new BufferedReader(new InputStreamReader(in));
os = new BufferedWriter(new OutputStreamWriter(out));
}catch(Throwable t){
t.printStackTrace();
}
}
public void run() {
System.out.println("Thread is running");
String dataType = "";
Boolean awaitingTransfer = false;
try {
while(true){
if(in.available() > 0 && !awaitingTransfer){
dataType = is.readLine();
System.out.println(dataType);
}
if(in.available() > 0 && awaitingTransfer){
try{
ArrayList<SpotCheck> tempList = new ArrayList<SpotCheck>();
while(in.available() > 0){
//tempList = (ArrayList<SpotCheck>) in.readObject();
}
ServerMain.manager.applyChanges(tempList);
awaitingTransfer = false;
}catch(Throwable t){
t.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
try {
in.close();
out.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Thanks for the help!
As an amateur coder, i just wanted to ask you that, can you just add a toast to the "catch()" blog of your doInBackground like that
catch(Exception e)
{
runOnUiThread(new Runnable(){
#Override
public void run(){
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
});
}
so it can show your problem more specifically and it will become easier to handle maybe. but again i am not sure if it works, i mean using toast in asynctask classes is a little bit more tricky.
i have watched a tutorial, and with the code of this, my phone phone chrashes every time it trys to send the text.
Client:
textField = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString();
textField.setText("");
try {
client = new Socket(InetAddress.getByName("jarves-server.no-ip.info"), 8000);
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Server:
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(8000);
} catch (IOException e) {
System.out.println("Could not listen on port");
}
System.out.println("Server started.");
while (true) {
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
}
}
}
I really don`t know what is wrong with the code. Maybe it could be also the DynDns i have set up with No-IP and our Speedport W723V and a Port forwarding on Port 8000 to my PC where the Server is running.
Hope for help!
If you had looked in the LogCat you would have seen a NetworkOnMainThreadException. You have to place your socket code in an AsyncTask or Thread.
I tried to write a simple server for an app that user can write a message from PC using telnet to IP and port. IT works just fine and it can show the
The problem is, when user closes telnet window (CMD window in PC, there is where user connects to app) the app stops.
Is there a way to prevent this behaviour? Here is my code:
//Defined in Activity class
//Sockets, servers, clients and stuff
public java.net.ServerSocket MyServerSocket;
public String IpAddress = "";
public int Port = 12345;
public Handler UpdateConversationHandler;
public Thread ServerThread = null;
Nested classes inside the Activity class:
class ServerThread implements Runnable{
public final String IpAddress;
public final int Port;
public ServerThread(String ipAddress, int port)
{
IpAddress = ipAddress;
Port = port;
}
public void run() {
Socket socket = null;
try{
MyServerSocket = new ServerSocket(Port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
try{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e){
e.printStackTrace();
}
}
public void run() {
while(!Thread.currentThread().isInterrupted()){
try{
String read = input.readLine();
UpdateConversationHandler.post(new UpdateUIThread(read));
} catch (IOException e){
e.printStackTrace();
}
}
}
}
class UpdateUIThread implements Runnable {
private String msg;
public UpdateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
_textview_info.setText("Client Says: "+ msg );
}
}
I also have this code for onStop method, but it doesn't help!
#Override
protected void onStop() {
super.onStop();
//Closing server socket
try
{
MyServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And this is the onCreate method, where the server starts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_context = this;
//Prepare spinners
_preferences = getSharedPreferences("org.pervasivesystems.nexusmosaic", MODE_PRIVATE);
_preferencesEditor = _preferences.edit();
_spinner_videos = (Spinner) findViewById(R.id.spinner_select_video);
_spinner_ids = (Spinner) findViewById(R.id.spinner_select_id);
populateSpinners();
//Prepare server
IpAddress = getIpAddress();
TextView tvIpAddress = (TextView) findViewById(R.id.textview_ip_address_value);
tvIpAddress.setText(IpAddress);
_textview_info = (TextView) findViewById(R.id.textview_information);
UpdateConversationHandler = new Handler();
ServerThread = new Thread(new ServerThread(IpAddress, Port));
this.ServerThread.start();
}
UPDATE
When I start the app, even before connecting from PC to app using telnet, I get the following message continuesly in LOGCAT:
11-14 15:45:32.460 W/System.err? at java.lang.Thread.run(Thread.java:856)
11-14 15:45:32.460 W/System.err? java.net.SocketException: Socket is closed
11-14 15:45:32.460 W/System.err? at java.net.ServerSocket.checkOpen(ServerSocket.java:362)
11-14 15:45:32.460 W/System.err? at java.net.ServerSocket.accept(ServerSocket.java:120)
11-14 15:45:32.460 W/System.err? at .MainActivity$ServerThread.run(MainActivity.java:233)
Line 233 is refering to this code:
while(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept(); //LINE 233
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
I also found out that after closing the telnet window from PC, the UpdateUiThread keeps running.
What is probably happening is that your communication thread is noticing the terminated connection and exits. This is how you wrote it. Im not sure what you want it to do instead...
If you want to do something after the terminated connection, just put some code right after
while(!Thread.currentThread().isInterrupted()){ ... }
Wait for the thread to finish, then do what you want.
Sometimes it helps me to add some system outs throughout threaded code to get a handle of when things are firing off/ending. It will help, trust me.
Try this
do{
if(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept();
if(socket!=null && socket.isConnected()){
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}while(socket!=null && socket.isConnected());
I've tried out almost everything.
Forwarding from ADB Shell using adb forward TCP:12345 TCP:12345
Using 10.0.2.2 (without forwarding) to listen to my host machine
Setting the INTERNET permission in the manifest
Setting the thread policy to permit all functions
I'm running my client java program in 12345 port and I have a ServerSocket in the Android program that listens over the same port. But when I run my client (after running the server program on the emulator) and enter the String that I want to transfer, I get the exception saying 'Connection Refused'.
java.net.ConnectException: Connection refused: connect
Here's my server program:
public class MainActivity extends Activity {
TextView tv;
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
public static final int SERVERPORT = 12345;
protected static final int MSG_ID = 0x1337;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = new TextView(this);
tv.setText("Nothing from client yet");
setContentView(tv);
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
// TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
setContentView(tv);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
My Java client program is as follows:
public class TCPSender {
public static void main(String args[]) {
try {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the file name:");
#SuppressWarnings("deprecation")
String f = dis.readLine();
File f1 = new File(f);
FileReader fr = new FileReader(f1);
Socket s = new Socket("127.0.0.1", 12345);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(f);
int c = 0;
while ((c = fr.read()) != -1)
pw.println(c);
System.out.println("File content are sent....");
fr.close();
s.close();
} catch (Exception e) {
System.out.println("" + e);
}
}
}