client can't send message from separate class - android

I created a socket program on android studio. First I create it with on the main class and it is working. With the help of this site I separate the connect and disconnect it works. Now there is a problem when the client send a message on the server. Whenever I put a letter, the output is just a blank space.
separate class
public class SocketClient extends Thread {
String serverm = null;
Socket client;
String Socketdata;
Context context;
String message;
String address;
public boolean mRun = true;
private PrintWriter printwriter;
public SocketClient (String address, Context context, String message )
{
this.address = address;
this.context = context;
this.message = message;
}
#Override
public void run(){
mRun = true;
try {
client = new Socket(address, 3818);
BufferedReader mBufferIn = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while (mRun) {
serverm = mBufferIn.readLine();
if (serverm != null) {
System.out.println(serverm);
Socketdata = serverm;
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopSocket()
{
if(client !=null)
{
Toast.makeText(context, "disconnected", Toast.LENGTH_LONG).show();
try {
client.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(context, "socket not found", Toast.LENGTH_LONG).show();
}
}
public void SendSocket()
{
if (message != null) {
try {
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(message + "\r\n"); // write the message to output stream
printwriter.flush();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(context, "sent", Toast.LENGTH_LONG).show();
}
}
Main class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.message); // reference to the text field
Connect = (Button) findViewById(R.id.connect); // reference to the connect button
Disconnect = (Button) findViewById(R.id.disconnect); // reference to the connect button
Send = (Button) findViewById(R.id.send); // reference to the send button
editTextAddress = (EditText) findViewById(R.id.address); // reference to the address
Disconnect.setOnClickListener(DisconnectOnClickListener);
Connect.setOnClickListener(ConnectOnClickListener);
Send.setOnClickListener(SendOnClickListener);
}
//Button Send
OnClickListener SendOnClickListener = new OnClickListener() {
public void onClick(View v) {
thread.SendSocket();
textField.setText(""); // Reset the text field to blank
}
};
//Button Disconnect
OnClickListener DisconnectOnClickListener = new OnClickListener() {
public void onClick(View v) {
thread.stopSocket();
}
};
//Button Connect
OnClickListener ConnectOnClickListener = new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"connected",Toast.LENGTH_LONG).show();
thread = new SocketClient(editTextAddress.getText().toString(), getApplicationContext(), textField.getText().toString());
thread.start();
}
};

Now I know what I'm missing. sorry for the inconvenience.
separate class
public void SendSocket(String newMessage ) {
if (newMessage != null) {
try {
printwriter = new PrintWriter(socket.getOutputStream(),true);
printwriter.write(newMessage + "\r\n"); // write the message to output stream
printwriter.flush();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
main class
View.OnClickListener SendOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
thread.SendSocket(textField.getText().toString());
}
};

Related

sockets doesn't work over wan

I am doing a simple chat application between two android devices using sockets (TCP connection) the problem is it works only over LAN but doesn't work over WAN how can i fix this problem ?
ClientSide::
public class MainActivity extends AppCompatActivity {
TextView tv_device, tv_receive, tv_transmit;
Button btn_connect, btn_GPS;
EditText et_IP_Address, et_port, et_message;
Socket S;
DataOutputStream DOS;
DataOutputStream DOS2;
DataInputStream DIS;
Thread TH;
Thread TH2;
String data;
int q=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_IP_Address= (EditText) findViewById(R.id.et_IP_Address);
et_port= (EditText) findViewById(R.id.et_port);
et_message= (EditText) findViewById(R.id.et_message);
et_message.setText("GPS");
btn_connect = (Button) findViewById(R.id.btn_connect);
btn_GPS= (Button) findViewById(R.id.btn_send);
tv_transmit=(TextView) findViewById(R.id.tv_transmit);
tv_receive = (TextView) findViewById(R.id.tv_receive);
tv_device = (TextView) findViewById(R.id.tv_device);
// connection
btn_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TH=new Thread(new Runnable() {
#Override
public void run() {
try {
S = new Socket(et_IP_Address.getText().toString(),Integer.parseInt(et_port.getText().toString()));
DOS = new DataOutputStream(S.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
});// End of thread
TH.start();
}
}); // end of buutton
// Sending
btn_GPS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TH2=new Thread(new Runnable() {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
DOS2 = new DataOutputStream(S.getOutputStream());
DOS2.writeUTF(et_message.getText().toString());
} catch (IOException e) {
e.printStackTrace();
}
tv_transmit.post(new Runnable() {
#Override
public void run() {
tv_transmit.setText(et_message.getText());
}
});
try {
DOS2.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
DIS = new DataInputStream(S.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
while (DIS!=null) {
try {
data = DIS.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
data = data.toString();
tv_receive.post(new Runnable() {
public void run() {
tv_receive.setText(data);
}
});
try {
DOS2.close();
DIS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}); // end of thread
TH2.start();
}
}); // end of button
}
#Override
protected void onStop() {
super.onStop();
try {
if(S != null)
S.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server Side::
public class MainActivity extends AppCompatActivity {
Thread TH;
String data;
Socket S;
ServerSocket ss;
DataOutputStream DOS;
String recieved="GPS";
String Response;
TextView et_port; TextView tv_receive; TextView tv_transmit; TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_port = (TextView) findViewById(R.id.et_port);
tv_receive = (TextView) findViewById(R.id.tv_receive);
tv_transmit = (TextView) findViewById(R.id.tv_transmit);
status = (TextView) findViewById(R.id.status);
Intent intent = new Intent(this, MyService.class);
startService(intent);
establishconnection();
}
public void establishconnection() {
TH = new Thread(new Runnable() {
#Override
public void run() {
status.setText(MyService.getIpAddress());
try {
ss = new ServerSocket(8080);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
S = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
status.post(new Runnable() {
#Override
public void run() {
status.setText("connected");
}
}
);
CommunicationThread commThread = null;
try {
commThread = new CommunicationThread(S);
} catch (IOException e) {
e.printStackTrace();
}
new Thread(commThread).start();
}
}
});
TH.start();
}
class CommunicationThread implements Runnable {
private Socket ClientSocket;
DataInputStream DIS;
public CommunicationThread(Socket ClientSocket) throws IOException {
this.ClientSocket = ClientSocket;
DIS = new DataInputStream(ClientSocket.getInputStream());
data = DIS.readUTF();
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
data = data.toString();
tv_receive.post(new Runnable() {
public void run() {
tv_receive.setText(data);
}
});
while (recieved.equals(data)) {
sendMessage();
try {
DOS = new DataOutputStream(S.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
if (Response !=null){
DOS.writeUTF(Response);
}
} catch (IOException e) {
e.printStackTrace();
}
tv_transmit.post(new Runnable() {
#Override
public void run() {
tv_transmit.setText(Response);
}
});
try {
DOS.flush();
DOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
S.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendMessage() {
Intent i = new Intent(this,Gps.class);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
// Bundle bundle = getIntent().getExtras();
if (data!=null) {
String x = data.getStringExtra("Latitude");
String y = data.getStringExtra("Longitude");
Response = x + "\n" + y;
}
}
}
}
}
Here the client suppose to send a word to server when the server recieves it it will open another intent and return back some data "GPS" to client

Socket client - server(android)

Sorry for my english. I am trying to create client and server. Now, my logic is like this:
I start app -> start server -> server listening to all messages -> if client sends message to server -> message goes to server -> message received by server -> server needs to send a message to all its customers.
But the server does not do this
** the server needs to send a message to all its customers**
or maybe
the client is not listening to the server.
my question: Why does the client not accept messages from the server?
//Main
//send message
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sendText.getText().toString().equals("")) {
return;
}
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg(sendText.getText().toString() + "\n");
}
});
//method create server and client, cliend connect to server
createServer(port);
}
public void createServer(int port) {
//create server
ChatServerThread chatServerThread = new ChatServerThread(port);
chatServerThread.start();
//subscribe to server 192.168.31.101 - ip server
createClient("Testov", "192.168.31.101", port);
}
//method for create client
public void createClient(String name, String ipAdress, int SocketServerPORT) {
chatClientThread = new ChatClientThread(
name, ipAdress, SocketServerPORT);
chatClientThread.start();
}
//this is server class
private class ChatServerThread extends Thread {
int SocketServerPORT;
public ChatServerThread(int SocketServerPORT) {
//set port
this.SocketServerPORT = SocketServerPORT;
}
#Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
//create server socket
serverSocket = new ServerSocket(SocketServerPORT);
//waite connect
socket = serverSocket.accept();
Log.e("connect", "server side");
//for input and output
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//listener
while(true) {
if (dataInputStream.available() > 0) {
//read line
String newMsg = dataInputStream.readUTF();
//send line to client
dataOutputStream.writeUTF(newMsg);
final String ms = newMsg;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
//end thread
dataOutputStream.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//this is client side
private class ChatClientThread extends Thread {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
String msgLog = "";
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
//set ip adress and port
socket = new Socket(dstAddress, dstPort);
//for get and post data
String mesageFromServer = null;
dataInputStream = new DataInputStream(socket.getInputStream());
while(!goOut) {
//wait message from server
mesageFromServer = dataInputStream.readUTF();
//output
Log.e("client", mesageFromServer);
final String ms = mesageFromServer;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
msgToSend = "";
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void sendMsg(String msg){
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
private void disconnect(){
goOut = true;
}
}

Searching the Server IP on Client instead of inputing

Server: PC
Client: Android
So my Client/Server app consists in opening webpages and executing a bot, everything is fine if I use only for a router, but I would like to be able to to connect in different places (different router/PC).
I was searching for "Wi-fi Search of IP" and got nothing.
Is it possible to give to the Server side a fix IP? like always 192.168.1.68?
Client Code
public class AndroidClient extends Activity
{
EditText episode;
Spinner spinner1;
String result;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
episode = (EditText) findViewById(R.id.episode);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
spinner1 = (Spinner) findViewById(R.id.Animes);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Anime, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
addListenerOnSpinnerItemSelection();
addListenerOnButton();
}
public void addListenerOnSpinnerItemSelection() {
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.Animes);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask();
myClientTask.execute();
}
});
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.1.3.68", 8080);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(episode.getText() + "-" + String.valueOf(spinner1.getSelectedItem()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Server Code
public class ServerSide extends Application
{
TextField textTitle;
Label labelSys, labelPort, labelIp;
Label labelMsg;
CheckBox optWelcome;
ServerSocket serverSocket;
String message = "";
String result;
#Override
public void start(Stage primaryStage) {
textTitle = new TextField();
labelSys = new Label();
labelPort = new Label();
labelIp = new Label();
labelMsg = new Label();
labelIp.setText(getIpAddress());
VBox mainLayout = new VBox();
mainLayout.setPadding(new Insets(5, 5, 5, 5));
mainLayout.setSpacing(5);
mainLayout.getChildren().addAll(textTitle,
labelSys, labelPort, labelIp,
labelMsg);
StackPane root = new StackPane();
root.getChildren().add(mainLayout);
Scene scene = new Scene(root, 300, 400);
primaryStage.setTitle("One Piece");
primaryStage.setScene(scene);
primaryStage.show();
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.setDaemon(true);
socketServerThread.start();
}
public static void main(String[] args) {
launch(args);
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
Socket socket = null;
serverSocket = new ServerSocket(SocketServerPORT);
Platform.runLater(new Runnable() {
#Override
public void run() {
labelPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
count++;
//Start another thread
//to prevent blocked by empty dataInputStream
Thread acceptedThread = new Thread(
new ServerSocketAcceptedThread(socket, count));
acceptedThread.setDaemon(true); //terminate the thread when program end
acceptedThread.start();
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class ServerSocketAcceptedThread extends Thread {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
int count;
ServerSocketAcceptedThread(Socket s, int c) {
socket = s;
count = c;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
//If dataInputStream empty,
//this thread will be blocked by readUTF(),
//but not the others
String messageFromClient = dataInputStream.readUTF();
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
Platform.runLater(new Runnable() {
#Override
public void run() {
labelMsg.setText(message);
}
});
String string = messageFromClient;
String[] parts = string.split("-");
String episode = parts[0];
String anime = parts[1];
String OneP = new String("One Piece");
String Naruto = new String ("Naruto");
String Bleach = new String ("Bleach");
int EPnumb = Integer.parseInt(episode);
if (EPnumb < 10) {
result = "00" + episode;
}
else if (EPnumb < 100 && EPnumb >= 10) {
result = "0" + episode;
}
else { result = episode; }
if (anime.equals(OneP)){
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/One-Piece/Episode-"+ result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}}
else {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/Naruto-Shippuuden/Episode-"+result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
private java.lang.String parseInt(java.lang.String episode) {
// TODO Auto-generated method stub
return null;
}
private String getIpAddress() {
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 ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
return ip;
}
public DataInputStream String(String string) {
return null;
}
}
You can use ServerSocket(int port, int backlog, InetAddress bindAddr)
Constructs a new ServerSocket instance bound to the given localAddress and port.

Connecting 2 android devices over internet

I'm trying to connect 2 android device (without server in the middle, just directly like peer-to-peer) which are connected to internet(they are far apart) and send messages.
I thought its like normal socket programming, and connects via IP, seems not.
what I have done so far is this:
I have created 2 android projects, server(receiver) and client(sender)
running in 2 separate devices
Both devices are connected to internet
found the IP of the device with server app running in (using whatismyip.com)
and used it in client app code
but when I want to send a text from client to server, an exception happens in client printing Error3
this is my code:
server:
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
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);
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();
}
}
}
}
}
Client (Error3):
public class MainActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "5.114.22.118";
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
private static final int REDIRECTED_SERVERPORT = 80;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
new Thread(new ClientThread()).start();
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I think this would be more appropriate as a comment, but I don't have enough reputation to comment so I'm providing it as an answer. Is your server connected to a router? whatismyip.com returns the IP address of the router, not the device.

Connecting emulator instances in android

I read a thread on the same topic : connecting 2 Emulator Instances
Server Side Code listening on port 6000:
public class NewServerActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
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);
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();
}
}
}
}
}
Client side code :
public class NewClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "10.0.2.2";
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
private static final int REDIRECTED_SERVERPORT = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
I applied server code on one emulator and client code on another emulator.
Redirected the ports :
telnet localhost 5554
redir add tcp:5000:6000
I ran the server on emulator 5554 and the client on 5556.
My client side is working fine but unfortunately, on starting the server app the emulator shows a message Unfortunately APPLICATION was stopped. And eclipse shows a java.lang.NullPointerException at "s = ss.accept();" line.
Is it somehow related to the configuration of my AVD.
Post your code and the stack trace.
From the one line you posted it sounds like 'ss' is null and you're trying to call accept() on a null.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void mOnClick(View v) {
switch (v.getId()) {
case R.id.myButton:
new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
Log.d("Client", "Client sent message");
out.close();
socket.close();
} catch (UnknownHostException e) {
//tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
//tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
//tv.setText("Error3");
e.printStackTrace();
}
}
}).start();
break;
}
}
need xml change
android:onClick="mOnClick"
<Button
android:id="#+id/myButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="mOnClick"
android:text="start" />
it's because try to run connect() method in main Thread

Categories

Resources