android socket internet - java

i got a little problem with my little application by using java Sockets.
if i start my Sockert-Server on pc and i'm connected withmy phone via wifi in the same network by using the (intern) network IP i can send some stuff to my server.
But if i try to send a message via the mobile internet connection,it doesn´t work..there is also no error or something else :/
Here is my android class:
public class Sockets extends Activity {
EditText textOut;
EditText ipAddress;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
ipAddress = (EditText)findViewById(R.id.ipAddress);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DatagrammClient(ipAddress.getText().toString(),textOut.getText().toString()).execute("");
textOut.setText("");
}};
private static class DatagrammClient extends android.os.AsyncTask<String, Void, String> {
final static String LOGIN = "LOGIN";
final static String LOGOUT = "LOGOUT";
static int port = 1234;
static int length = 1024; // Länge eines Pakets
static DatagramSocket socket = null;
static InetAddress ia = null;
static DatagramPacket packet;
String hostname = "";
String msg ="";
public DatagrammClient(String hostname,String msg) {
this.hostname = hostname;
this.msg = msg;
}
/**
* Send the login package and open socket
*
* #param servername
* #throws IOException,UnknownHostEception
*/
private static void connectToServer(String servername) throws IOException,UnknownHostException{
packet = null;
byte[] ba = LOGIN.getBytes();
try {
socket = new DatagramSocket();
ia = InetAddress.getByName(servername);
packet = new DatagramPacket(ba, ba.length, ia, port);
Log.d("servername",servername);
Log.d("Internetaddress",ia.toString());
Log.d("SOCKET",socket.toString());
// sende Anmeldung
socket.send(packet);
} catch (SocketException se) {
Log.d("SocketException",se.toString());
}
catch (UnknownHostException he) {
Log.d("UnknownHost: ",he.toString());
}
catch (IOException e) {
Log.d("IOException: ",e.toString());
}
}
public static void sendMessage(String message, String hostname) throws UnknownHostException, IOException{
//if (socket == null){
DatagrammClient.connectToServer(hostname);
//}
DatagrammClient.sendMessageToServer(message);
DatagrammClient.readMessageFromServer();
//Close connection -> Send logout Package?
}
private static void readMessageFromServer(){
// Lesen der empfangenen Pakete erfolgt in eigenem Thread
LeseThread lt = new LeseThread( socket );
}
private static void sendMessageToServer(String message){
byte[] ba = null;
try {
if (!message.equals(LOGOUT)) {
// message = br.readLine();
ba = message.getBytes();
packet.setData(ba, 0, ba.length);
socket.send(packet);
Log.d("Message:",packet.toString());
} else {
ba = LOGOUT.getBytes();
packet.setData(ba, 0, ba.length);
socket.send(packet);
// Exit the system -> do we need to close the socket clientside?
//socket.close();
System.exit(0);
}
} catch (IOException e) {
System.err.println("Ausnahmefehler: " + e);
Log.d("IOEXCEPTION_MESSAGE_TO_SERVER:",e.toString());
}
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
DatagrammClient.sendMessage(msg, hostname);
}
catch(Exception e){
Log.d("Error: ",e.toString());
}
return null;
}
}
}
The permission to use the INTERNET is set in the Manifest..

Related

How can I send a String through socket from client then get the return from the server?

I am trying to make a simple java android app
I want to send an order from my computer (client) to my android app (server) the the mobile (server) must send the return back to the client (computer)
Client (computer)
public class Main {
public static void main(String[] args) {
Scanner sx = new Scanner(System.in);
String ln = sx.next();
try {
Socket s = new Socket("192.168.2.2", 4040);
s.setSoTimeout(4000);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(ln);
dos.flush();
s.close();
System.out.println("Done....");
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Server (android app)
public class MainActivity extends Activity {
EditText portfield, ipfield;
LinearLayout player;
SharedPreferences sp;
SharedPreferences.Editor ed;
String myip, myport;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = (LinearLayout) findViewById(R.id.player);
portfield = (EditText) findViewById(R.id.portfield);
ipfield = (EditText) findViewById(R.id.ipfield);
sp = getSharedPreferences("okayawalas2423", MODE_PRIVATE);
ed = sp.edit();
myport = sp.getString("myport", null);
myip = sp.getString("myip", null);
runit();
}
public void runit() {
if (myport != null && myip != null) {
final String myport;
final String myip;
startspy();
}
}
public void startspy() {
player.removeAllViews();
Thread th = new Thread(new Runnable() {
public void run() {
eim();
}
});
th.start();
}
public void eim() {
try {
ServerSocket server = new ServerSocket(Integer.parseInt(myport));
say("Server Connected Successfully .... ");
while (true) {
Socket skt = server.accept();
say("The Server Request Has Been Accepted .... ");
DataInputStream dis = new DataInputStream(skt.getInputStream());
String purein = dis.readUTF();
dsay("Data Has Been Sent Right Now To /// and it contains : \n [[[ " + dis.readUTF() + " ]]]");
DataOutputStream dos = new DataOutputStream(skt.getOutputStream());
String outword = doit(purein);
dos.writeUTF(outword);
dos.flush();
dis.close();
dos.close();
skt.close();
}
} catch (Exception e) {
TextView tz = new TextView(this);
tz.setText(e.toString());
player.setGravity(Gravity.CENTER);
player.addView(tz);
}
}
public void stt(View v) {
if (portfield.getText().toString().equals("") || ipfield.getText().toString().equals("")) {
Toast.makeText(this, "Insert All Data !!", Toast.LENGTH_LONG).show();
} else {
ed.putString("myport", portfield.getText().toString());
ed.putString("myip", ipfield.getText().toString());
ed.commit();
startspy();
}
}
public String doit(String p) {
String funRes = "none";
funRes = p;
return funRes;
}
public void say(String s) {
TextView tz = new TextView(this);
tz.setText(s);
player.setGravity(Gravity.CENTER);
player.addView(tz);
}
public void dsay(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
}
I type the message on the computer (client) when I press ENTER, I get the "Done..." but the android app gets down!!

Android Client and Java server 'Java.net.ConnectException'

I made a super simple server on my Windows Machine that waits for a client, and when connected, all it does is get a message and prints it to the Console.
When I run a Server code on my computer, and then run another Client application, it works fine. However, when I run the exact same client code(except for a few changes that are necessary) on my Android Phone(connected via USB), it doesn't work.
The IP address for my PC is correct and the port is free, I've been getting this error message:
W/System.err: java.net.ConnectException: failed to connect to /192.168.10.104 (port 1755) from /:: (port 42102): connect failed: ETIMEDOUT (Connection timed out)
My server.java that runs on my PC is
import java.net.*;
import java.io.*;
public class Server {
// Initialize everything
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in =null;
//constructor with port
public Server(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started, waiting for Client...");
socket = server.accept();
System.out.println("Client accepted");
in =new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
while (!line.equals("Over")) {
try {
line = in.readUTF();
System.out.println(line);
}
catch(IOException e) {
System.out.println(e);
}
}
System.out.println("Closing connection");
//CLosing connections
socket.close(); in .close();
}
catch(IOException e) {
System.out.println(e);
}
}
public static void main(String[] args) {
Server server = new Server(1755);
}
}
This is the client code
import java.io.*;
import java.net.*;
public class MainActivity extends AppCompatActivity {
TextView Message_shower;
EditText text_place;
TextView messageStatus;
Button send_btn;
// Initialize sockets and IO streams
Socket socket = null;
DataOutputStream out = null;
private static final int SERVERPORT = 1755;
private static final String SERVER_IP = "192.168.10.104";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_place = findViewById(R.id.editText);
messageStatus = findViewById(R.id.messageStatus);
send_btn = findViewById(R.id.send_btn);
// Shows recent sent message
Message_shower = findViewById(R.id.Message_shower);
// Establish a connection
send_btn.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
new Sender().execute();
}
});
}
// Close connections
private void onClose() {
try {
if (socket != null) {
out.close();
socket.close();
}
}
catch(IOException e) {
System.out.println(e);
}
}
class Sender extends AsyncTask < Void,
Void,
Integer > {
private Exception e1;
private Exception e2;
String input;
#Override
protected void onPreExecute() {
EditText text_place = findViewById(R.id.editText);
// Takes input from terminal
input = text_place.getText().toString();
Message_shower.setText(input);
System.out.println("Reached here\n");
}
#Override
protected Integer doInBackground(Void...params) {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
// Sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(Exception e) {
this.e1 = e;
}
try {
out.writeUTF(input);
} catch(Exception h) {
this.e2 = h;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (e1 != null) {
e1.printStackTrace();
}
if (e2 != null) {
e2.printStackTrace();
}
TextView txt = findViewById(R.id.messageStatus);
txt.setText("Message Sent");
text_place.setText("");
onClose();
}
}
}
All input is very appreciated, I've tried various ways like turning off the firewall and such but none worked.

Sending commands from phone to computer via Sockets

I'm trying to send commands from my phone to my computer using Sockets.
I've tryed the answers here:
Android and PC Socket connection
But after some digging i found out that you need to use a Async task so i tryed this:
Using AsyncTask for android network connection
But for some reason my socket times out. Is there a way to find out why? because from the error i can't tell:
The error from Logcat:
And this is the client code:
public class MainActivity extends AppCompatActivity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message;
private static final int SERVERPORT = ####;
private static final String SERVER_IP = "########";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
}
public void onClick(View view) {
message = textField.getText().toString();
textField.setText(""); // Reset the text field to blank
new AsyncAction().execute();
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
System.out.println("background running");
System.out.println(message);
client = new Socket(SERVER_IP, SERVERPORT); // connect to server
System.out.println(client.isConnected());
System.out.println("test");
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(message); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
I wrote a Server for this in Java and tested it in the emulator.
I had two things to do :
The server IP is "10.0.2.2" if you are using an Android Emulator. LocalHost is de Emulator Virtual Machine.
Your application needs Permission Internet in manifest
Here is the server Code
/**
*
* #author Jean-Pierre
*/
public class SocketServer {
private static final int portnumber = 4444;
public static void main(String[] args) {
SocketServer socketServer = new SocketServer();
socketServer.run();
}
/**
* Reads a String from the client
* Converts it to Uppercase
* and sends it Back.
*/
private void run() {
try {
ServerSocket serverSocket = new ServerSocket(portnumber);
Socket clientSocket = serverSocket.accept();
System.out.println("connected with :" + clientSocket.getInetAddress());
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
InputStreamReader is =
new InputStreamReader(clientSocket.getInputStream());
BufferedReader in =
new BufferedReader(is);
while (true) {
String line = in.readLine();
if (line != null) {
System.out.println("recieved:" + line);
out.println(line.toUpperCase());
}
}
} catch (IOException ex) {
Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Implementing Virtual Keyboard Android to PC

I'm attempting to use my android phone as a keyboard for my PC.
This is done over a local WiFi connection using sockets to create the client/server connection.
I'm using a textwatcher to pick up the change in characters in an editText and then sending those over to the server which then uses a robot class to write that onto the PC. This is all using a Softkeyboard on the android phone.
The issue is that when writing in editText only one character gets sent. and picked up by the server.
e.g. I type on the android phone "a" and the respective keypress will be simulated on the server. If I then type another character it does not read that character but if I delete the "a" and then type another character it will send that character.
Below is the Client side of the code, the Android application.
public class MainActivity extends AppCompatActivity implements View.OnKeyListener {
private final static int portNumber = ****;
private final static String hostName = "192.168.0.8";
private final static String cTest = "Connection Test";
Socket socket = null;
private static String TAG = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
#Override
public void run() {
try {
Log.i(cTest, "attempting to connect");
socket = new Socket(hostName, portNumber);
Log.i(cTest, "Connected");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Connected Successfully", Toast.LENGTH_SHORT).show();
}
});
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(editTextWatcher);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(cTest, e.getMessage());
}
}
}.start();
}
private TextWatcher editTextWatcher = new TextWatcher() {
private void sendTextToServer(String send) {
BufferedWriter bw = null;
String textChange = send;
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(textChange);
bw.newLine();
bw.flush();
} catch (IOException e) {
}
}
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
Log.d(TAG, s + " Character Read");
String test = s.toString();
this.sendTextToServer(test);
}
};
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
}
The following code is the server side code which is being done in eclipse.
public class ListenServerMain {
private static boolean ifConnected = true;
private final static int portNumber = ****;
public static String readIn;
private static Socket client = null;
private static ServerSocket server = null;
private static BufferedReader in = null;
private static Robot robot = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
robot = new Robot();
server = new ServerSocket(portNumber);
System.out.println("Listening on port :****");
client = server.accept(); //loops until a client server connection is established
System.out.println("Client connected");
//Receive a message from the client
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while(ifConnected)
{
readIn = in.readLine(); //reads the input received
if(readIn.equalsIgnoreCase("A"))
{
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
}
if(readIn.equalsIgnoreCase("B"))
{
robot.keyPress(KeyEvent.VK_B);
robot.keyRelease(KeyEvent.VK_B);
}
if(readIn.equalsIgnoreCase("C"))
{
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
}
if(readIn.equalsIgnoreCase("BS"))
{
robot.keyPress(KeyEvent.VK_DELETE);
robot.keyRelease(KeyEvent.VK_DELETE);
}
}
System.out.println("Unable to read user Input"); //if it can't read the input from the Client
System.exit(-1); //system exits
System.out.println("Server Ended");
System.exit(-1);
}
catch (IOException e) {
System.out.println("Can't open the Socket");
System.exit(-1);
}
catch (AWTException e) {
System.out.println("Unable to create Robot");
System.exit(-1);
}
}
}
Is there any way in which I can successfully read and send each character entered in the editText field?
If any further clarification about this is necessary let me know.
Thanks

Server Ip at Client side using Sockets

I need to create an application using android socket level programming, I created a connection between server and client but I need to show waiting server IP list at client side and select one IP from the list and establish a connection between them.
Here is my code for server side
public class Server extends AppCompatActivity {
private static final String TAG = "ServerActivity";
private TextView tvServerStatus;
private TextView recievemsg;
InetAddress receiverAddress;
public static String SERVERIP = "";
DatagramSocket datagramSocket;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
Handler updateConversationHandler;
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
updateConversationHandler = new Handler();
tvServerStatus = (TextView) findViewById(R.id.tvServerStatus);
recievemsg=(TextView)findViewById(R.id.send_msg);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = "0123456789".getBytes();
byte[] address=SERVERIP.getBytes();
receiverAddress = InetAddress.getByAddress(address);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, receiverAddress, 8080);
datagramSocket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLocalIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerThread implements Runnable {
#Override
public void run() {
try {
Log.e(TAG, "Server IP: " + SERVERIP);
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Listening On Ip: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
{
try {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(client);
new Thread(commThread).start();
// Log.e(TAG, "Client Socket: " + client);
// new Clients_Handle(client, ROOT_DIRECTORY).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Error");
}
});
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() {
recievemsg.setText(recievemsg.getText().toString() + "Client Says: " + msg + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
Log.e(TAG,"Socket Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is my client side code
public class Clientss extends AppCompatActivity {
private static final String TAG = "Client_Activity";
private EditText etServerIp;
private EditText etMsg;
private Button btnConnectClients;
private Button btnSendMsg;
private TextView textIn;
private String serverIpAddress = "";
private String t;
private boolean connected = false;
DatagramSocket datagramSocket;
DatagramPacket packet;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientss);
Log.e(TAG, "ONCREATE METHOD");
textIn = (TextView)findViewById(R.id.txt_msg);
initializations();
eventClickListener();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = new byte[10];
packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);
byte[] buff = packet.getData();
textIn.setText(buff.toString());
System.out.println("this is incoming ip"+buff.toString());
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// textIn.setText(t);
}
private void eventClickListener() {
btnConnectClients.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = etServerIp.getText().toString().trim();
connectsClient();
}
}
});
btnSendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMsg.getText().toString().trim();
ClientResponseTask clientResponseTask=new ClientResponseTask(msg);
clientResponseTask.execute();
}
});
}
private void connectsClient() {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
private void initializations() {
etServerIp = (EditText) findViewById(R.id.etServerIp);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSendMsg = (Button) findViewById(R.id.btnMsgSend);
btnConnectClients = (Button) findViewById(R.id.btnConnect);
}
private class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.e(TAG, "C: Connecting...");
socket = new Socket(serverAddr, Server.SERVERPORT);
System.out.println("this is socket"+socket);
connected = true;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
//showToast("");
Log.e(TAG, "C: Connected..." + socket);
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
connected = false;
}
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
Toast.makeText(getApplicationContext(),"Connected...", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onDestroy() {
if (socket != null) try {
socket.close();
Log.e(TAG, "C: Socket Closed.");
} catch (IOException e) {
e.printStackTrace();
} finally
{
try
{
socket.close();
}
catch(Exception e){}
}
super.onDestroy();
}
protected class ClientResponseTask extends AsyncTask<Void,Void,Void> {
String msg;
ClientResponseTask(String msg){
this.msg=msg;
}
#Override
protected Void doInBackground(Void... params) {
if (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
else {
connectsClient();
}
return null;
}
}
}
Please help me to find a solution.

Categories