java.net.socket ConnectException ETIMEEDOUT - java

I'm trying to connect server socket using android. Please check the code below. I'm trying to send data from android to server as well as send data back to android from server but it is causing timeout exception at android side.
package com.example.orderdish;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MenuActivity extends Activity {
Button vegButton, nonVegButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
vegButton = (Button) findViewById(R.id.btn_veg);
nonVegButton = (Button) findViewById(R.id.btn_non_veg);
}
public void openCategory(View view) {
Button button = (Button)view;
Toast.makeText(getApplicationContext(), button.getText().toString() + " selected", Toast.LENGTH_LONG).show();
//Intent intent = new Intent(getApplicationContext(), ListCategoryActivity.class);
//startActivity(intent);
MyClientTask myClientTask = new MyClientTask(
"my ip",
1234);
myClientTask.execute();
}
public class MyClientTask extends AsyncTask<Void, Void, String> {
String dstAddress;
int dstPort;
String response = "";
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected String doInBackground(Void... arg0) {
Socket socket = null;
try {
Timer timer = new Timer(3000);
timer.start();
//Connect to remote host
socket = new Socket(dstAddress, dstPort);
Log.v("MenuActivity: ", "Connected to 1234 port");
//Reset timer - timeout can occur on connect
// InputStream inputStream = socket.getInputStream();
//create data output stream for writing
PrintStream pout = new PrintStream(socket.getOutputStream());
//dataOutputStream = new DataOutputStream(socket.getOutputStream());
// dataOutputStream.writeUTF("v");
//create data input stream for reading
DataInputStream din = new DataInputStream(socket.getInputStream());
//Print hello message
pout.println("Hello world");
//Reset timer - timeout is likely to occur during the read
timer.reset();
//print message from server
// dataInputStream = new DataInputStream(socket.getInputStream());
// response = dataInputStream.readUTF();
// Log.v("MenuActivity", "hi.." + dataInputStream.readUTF());
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = din.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
Log.v("MenuActivity ", response);
timer.stop();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
// textResponse.setText(response);
Log.v("MenuActivity", result);
super.onPostExecute(result);
}
}
}
package com.orderdish.main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import com.google.gson.Gson;
public class Test {
// List<Menu> menuList;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
String str;
List<Menu> menuList;
try {
serverSocket = new ServerSocket(1234);
socket = serverSocket.accept();
System.out.println("Server has connected!\n");
socket.setSoTimeout(100000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((str = br.readLine()) != null) {
System.out.println("The message: " + str.trim());
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Sending string ... sample data\n");
out.println("sample data");
out.close();
br.close();
socket.close();
serverSocket.close();
} catch(Exception e) {
System.out.println("Whoops! It didn't work!\n : " + e.getMessage().toString());
}
}
}

**Please find the modified code**
package com.example.orderdish;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MenuActivity extends Activity {
int current = 0;
Context ctx;
Button vegButton, nonVegButton;
String ip = "XXX.XXX.X.XX"; //Server IP
int portNo = 1234; //Port no.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
ctx = getApplicationContext();
vegButton = (Button) findViewById(R.id.btn_veg);
nonVegButton = (Button) findViewById(R.id.btn_non_veg);
vegButton.setOnClickListener(buttonConnectOnClickListener);
nonVegButton.setOnClickListener(buttonConnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View view) {
MyClientTask myClientTask = new MyClientTask(
ip, portNo);
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, String> {
String dstAddress;
int dstPort;
String menuType;
String response = "";
String received_message;
MyClientTask(String addr, int port){
dstAddress = addr; //server ip
dstPort = port; //server port
}
#Override
protected String doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
DataOutputStream pout = new DataOutputStream(socket.getOutputStream());
pout.writeUTF(menuType);
DataInputStream dis = new DataInputStream(socket.getInputStream());
received_message = DataInputStream.readUTF(dis);
pout.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return received_message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
package com.orderdish.main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
public class Test {
public final static int SOCKET_PORT = 1234;
public static DataInputStream dis;
public static DataOutputStream dos;
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(SOCKET_PORT);
while(true) {
System.out.println("Waiting...");
try {
socket = serverSocket.accept();
System.out.println("Accepted connection: " + socket);
//Here is the change
dis = new DataInputStream(socket.getInputStream());
String received_message = DataInputStream.readUTF(dis);
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("sample data");
} catch(Exception e) {
System.out.println("Whoops! It didn't work!\n");
} finally {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(socket != null)
socket.close();
}
}
} finally {
if(serverSocket != null) serverSocket.close();
}
}
}

Related

Socket Server controller Android App, Socket error

So basically I want to create some kind of controller for my pc, where on pc, runs java socket server. The server is working, I have tried it. Also, Port Forwarding in the router is allright. Source code is here :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_BOLD = "\033[1m";
public static final String ANSI_RED = "\u001B[31m";
public static void main(String[] args) throws IOException {
// Creating server instance
ServerSocket serverSocket = new ServerSocket(2000);
Socket socket = serverSocket.accept();
System.out.println(ANSI_GREEN + "Controller connected" + ANSI_RESET);
// Input Output streams
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String command = "";
do {
command = dataInputStream.readUTF();
switch (command.trim()){
case "volume up":
Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\volup.bat");
break;
case "volume down":
Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\voldown.bat");
break;
default:
// Unknown command
break;
}
}while (!command.equals("stop"));
socket.close();
System.out.println(ANSI_RED + "Controller disconnected" + ANSI_RESET);
}
}
And it is supposed to interact with the android app, but I got an error and I can't quite figure out why is that so, here is the source code for ActivityMain :
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private boolean connected;
private DataOutputStream dataOutputStream;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pripájanie na server
try {
socket = new Socket("172.0.0.1",2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Not Connected!",
Toast.LENGTH_LONG).show();
}
Button VolumeUp = (Button) findViewById(R.id.VolumeUpButton);
VolumeUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("volume up");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button VolumeDown = (Button) findViewById(R.id.VolumeDownButton);
VolumeDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("volume down");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button DisconnectButton = (Button) findViewById(R.id.DisconnectButton);
DisconnectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("stop");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void send(String command) throws IOException {
if (socket != null){
dataOutputStream.writeUTF(command);
}
else Toast.makeText(MainActivity.this, "Socket is not defined",
Toast.LENGTH_SHORT).show();
}
public void disconnect() throws IOException {
if (socket != null){
socket.close();
}
else Toast.makeText(MainActivity.this, "Socket is not defined",
Toast.LENGTH_SHORT).show();
}
}
So if you could help me with it, I would be thankful, <3
Well the reason for that was silly. When I'm loading data from Stream it says nextLine which means the ending point is \n so I could never get that line because I haven't put it there.

Android Socket is showing "Connected" when a Client Request connection but "cant send messages"

So,It's like the title Say's i have created a Simple android Socket server and Client which Connects over Wifi. Both devices are on the same Wifi Network. The Server Shows the IP Address on which it host the connection....And in the client You have to write the IP Address on which Server is hosted.....
So, My problem is when i am Entering The IP Address in the Client The Server shows "Connected". But when i start to send messages it doesn't send the message to other side neither Server to Client nor Client to server.
//#Server Java File
package inc.teckzy.wif_chat;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Helper extends AppCompatActivity {
EditText smessage;
TextView chat,display_status;
String str,msg="";
int serverport = 6666;
ServerSocket serverSocket;
Socket client;
Handler handler = new Handler();
WifiManager wmanager;
Boolean Alive;
DataOutputStream out;
DataInputStream in;
Button button_sent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helper);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
#SuppressWarnings("deprecation")
String ip = Formatter.formatIpAddress(wmanager.getConnectionInfo().getIpAddress());
smessage = (EditText) findViewById(R.id.smessage);
chat = (TextView) findViewById(R.id.chat);
display_status = (TextView) findViewById(R.id.display_status);
Thread serverThread = new Thread(new serverThread());
serverThread.start();
Alive = serverThread.isAlive();
display_status.setText("Hosted on: " + ip);
button_sent = (Button) findViewById(R.id.button_sent);
button_sent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
}
class sentMessage implements Runnable{
#Override
public void run() {
try{
client = serverSocket.accept();
out = new DataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
msg = msg+"\n Server:" +str;
handler.post(new Runnable()
{
#Override
public void run()
{
chat.setText(msg);
}
});
out.writeBytes(str);
out.flush();
out.close();
client.close();
}catch(IOException e){}
}
}
public class serverThread implements Runnable {
#Override
public void run() {
try {
while (true) {
serverSocket = new ServerSocket(serverport);
client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
display_status.setText("Connected");
}
});
/*******************************************
setup i/p streams
******************************************/
in = new DataInputStream(client.getInputStream());
String line = in.readUTF();
while (!line.equals("STOP")) {
msg = msg + "\n Client : " + line;
handler.post(new Runnable() {
#Override
public void run() {
chat.setText(msg);
}
});
}
in.close();
client.close();
}
} catch (Exception e) {
}
}
}
}
//#Client Side Java File
package reciever;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.*;
import java.net.*;
import inc.teckzy.wif_chat.R;
public class ClientSide extends AppCompatActivity {
EditText serverIp,smessage;
TextView chat;
String serverIpAddress = "",msg = "",str;
Handler handler = new Handler();
Button sent,connectPhones;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_side);
chat = (TextView) findViewById(R.id.chat);
serverIp = (EditText) findViewById(R.id.server_ip);
smessage = (EditText) findViewById(R.id.smessage);
sent = (Button) findViewById(R.id.sent_button);
connectPhones = (Button) findViewById(R.id.connect_phones);
//-----------------------Connecting to IP------------------------------//
connectPhones.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals(""))
{
Thread clientThread = new Thread(new
ClientThread());
clientThread.start();
}
}
});
//-------------------------------Initializing sent thread----------------//
sent.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
}
class sentMessage implements Runnable
{
#Override
public void run()
{
try
{
InetAddress serverAddr =
InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, 6666); //
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
str = smessage.getText().toString();
str = str + "\n";
msg = msg + "Client : " + str;
handler.post(new Runnable() {
#Override
public void run() {
chat.setText(msg);
}
});
os.writeUTF(str);
os.flush();
os.close();
socket.close();
}
catch(IOException e)
{
}
}
}
public class ClientThread implements Runnable
{
InetAddress serverAddr;
public void run()
{
try
{
while(true)
{
serverAddr = InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, 6666);
/*******************************************
setup i/p streams
******************************************/
DataInputStream in = new
DataInputStream(socket.getInputStream());
String line = in.readUTF();
while (!line.equals("Stop"))
{
msg = msg + "Server : " + line + "\n";
handler.post(new Runnable()
{
#Override
public void run()
{
chat.setText(msg);
}
});
}
in.close();
socket.close();
Thread.sleep(100);
}
}
catch (Exception e)
{}
}
}
}
You are using client = serverSocket.accept(); in server side every time you need to send a message.
And in client side you are trying to create a new Socket connection using new Socket
(serverAddr, 6666); multiple times.
Maintain a single Socket connection and single data input/output stream(do not create multiple instances) and you will be good to go.
See example at:
https://github.com/nabinbhandari/android-socket-messaging
I Solved it Just deleted the "sentMessage" Thread and implemented output stream in "sent.setOnClickListener(new View.OnClickListener()" in both Activity also did some modifications..Here is the working code Activity ...Hope this will help someone
#Server Activity
package inc.teckzy.wifi_chat;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Helper extends AppCompatActivity {
EditText smessage;
TextView chat,display_status;
String str,Smsg,Cmsg="";
int serverport = 6666;
ServerSocket serverSocket;
Socket client;
Handler updateConversationHandler =new Handler();
WifiManager wmanager;
DataOutputStream out;
DataInputStream in;
Button button_sent;
StringWriter errors = new StringWriter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helper);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
#SuppressWarnings("deprecation")
String ip = Formatter.formatIpAddress(wmanager.getConnectionInfo().getIpAddress());
smessage = (EditText) findViewById(R.id.smessage);
chat = (TextView) findViewById(R.id.chat);
display_status = (TextView) findViewById(R.id.display_status);
Thread serverThread = new Thread(new serverThread());
serverThread.start();
display_status.setText("Hosted on: " + ip);
button_sent = (Button) findViewById(R.id.button_sent);
button_sent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
out = new DataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
Smsg = "Server:" + str;
updateConversationHandler.post(new updateUIThread(Smsg));
out.writeUTF(str);
out.flush();
}catch (Exception e) {
e.printStackTrace(new PrintWriter(errors));
updateConversationHandler.post(new updateUIThread(errors.toString()));
}
smessage.getText().clear();
}
});
}
public class serverThread implements Runnable {
#Override
public void run() {
try {
serverSocket = new ServerSocket(serverport);
while (true) {
client = serverSocket.accept();
updateConversationHandler.post(new updateUIThread("Connected"));
/*******************************************
setup i/p streams
******************************************/
in = new DataInputStream(client.getInputStream());
String line = "";
while (!line.equals("STOP")) {
line=in.readUTF();
Cmsg ="Client: "+ line;
updateConversationHandler.post(new updateUIThread(Cmsg));
}
in.close();
client.close();
}
} catch (Exception e) {
e.printStackTrace(new PrintWriter(errors));
updateConversationHandler.post(new updateUIThread(errors.toString()));
}
}
}
class updateUIThread implements Runnable {
private String msg;
updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
chat.setText(chat.getText().toString()+ msg + "\n");
}
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And
#Client Activity
package inc.teckzy.wifi_chat.reciever;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.Socket;
import inc.teckzy.wifi_chat.R;
public class ClientSide extends AppCompatActivity {
EditText serverIp,smessage;
TextView chat;
String serverIpAddress = "",Smsg,Cmsg = "",str;
Handler updateConversationHandler = new Handler();
Button sent,connectPhones;
Socket socket;
DataInputStream in;
DataOutputStream out;
StringWriter errors = new StringWriter();
WifiManager wmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_side);
chat = (TextView) findViewById(R.id.chat);
serverIp = (EditText) findViewById(R.id.server_ip);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
smessage = (EditText) findViewById(R.id.smessage);
sent = (Button) findViewById(R.id.sent_button);
connectPhones = (Button) findViewById(R.id.connect_phones);
//-----------------------Connecting to IP------------------------------//
connectPhones.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals(""))
{
Thread clientThread = new Thread(new
ClientThread());
clientThread.start();
}
}
});
//-------------------------------Initializing sent thread----------------//
sent.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try {
out = new DataOutputStream(socket.getOutputStream());
str = smessage.getText().toString();
Cmsg = "Client: " + str;
updateConversationHandler.post(new updateUIThread(Cmsg));
out.writeUTF(str);
out.flush();
}catch(Exception e){
e.printStackTrace(new PrintWriter(errors));
updateConversationHandler.post(new updateUIThread(errors.toString()));}
smessage.getText().clear();
}
});
}
public class ClientThread implements Runnable
{
InetAddress serverAddr;
public void run()
{
try
{
serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, 6666);
updateConversationHandler.post(new updateUIThread("Connected"));
String ip = socket.getRemoteSocketAddress().toString();
updateConversationHandler.post(new updateUIThread(ip));
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
/*******************************************
setup i/p streams
******************************************/
String line = "";
while (!line.equals("Stop")) {
line=in.readUTF();
Smsg ="Server: " + line + "\n";
updateConversationHandler.post(new updateUIThread(Smsg));
}
out.close();
in.close();
socket.close();
}
catch (IOException e)
{updateConversationHandler.post(new updateUIThread("IO Error"));}
}
}
class updateUIThread implements Runnable {
private String msg;
updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
chat.setText(chat.getText().toString()+ msg + "\n");
}
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java android send a message using socket

Hi I want to send a message using a socket I have this :
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("Hello World!");
// Read data
// DataInputStream inputStream = new DataInputStream(socket.getInputStream());
// message = inputStream.readUTF();
// Shut down socket
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
OutputStream out = socket.getOutputStream();
out.write("some data".getBytes());
out.flush();
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
When I click a button only connected to the server. It don't send a message. What I have to do for send something ? maybe a message "Hello world" ?
I'm not sure what the point of your program is but your output and input system seems fairly messy. You need a DataOutputStream to send data and a DataInputStream to receive data from and to the socket.
I've attached the system I use which is a lot simpler:
try {
// Establish connection
Socket socket = new Socket("IP ADDRESS HERE", PORT_NUMBER);
// Request data
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("Hello World!");
// Read data
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
message = inputStream.readUTF();
// Shut down socket
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException io) {
io.printStackTrace();
}
NB: You can change readUTF to readByte or several other alternatives as appropriate.

how can i send my message from android client to other android client using my socket java PC server

i have my code that sucessfuly send my client message to server.. can anyone help pls ? i'm new in socket programming. i want to establish a server that sends the message of my android client to other android client... here is my code
CLIENT ANDROID :
package com.example.websocketclient;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Chatroom extends Activity {
public static String msgToServer = null;
TextView uname;
EditText in;
Button snd;
TextView out;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatroom);
uname = (TextView) findViewById(R.id.textViewmynam);
in = (EditText) findViewById(R.id.editTextInput);
snd = (Button) findViewById(R.id.buttonSend);
out = (TextView) findViewById(R.id.textViewOutput);
Bundle bundle = getIntent().getExtras();
String urname = bundle.getString("myname");
uname.setText(urname);
MyClientTask clientTask = new MyClientTask();
clientTask.execute();
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
connect();
return null;
}
}
public void connect() {
Socket sock;
int[] allports = {1111,1919,2020};
int portnum;
for(int i=1;i<allports.length;i++) {
try {
portnum = allports[i];
boolean socketno = Middleware.available(portnum);
String ad = "192.168.149.1";
if(socketno = true) {
sock = new Socket(ad,portnum);
while(socketno) {
sendmsg(sock);
}//while
// sock.close();
}//if
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendmsg (final Socket s) {
snd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//boolean listening = true;
String inmsg = ""+in.getText().toString();
String response = "";
msgToServer = inmsg;
//out.append("you:"+msgToServer+"\n");
try {
DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
DataInputStream inToServer = new DataInputStream(s.getInputStream());
if(outToServer != null){
outToServer.writeBytes(msgToServer+"\n");
}
}
catch (Exception e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chatroom, menu);
return true;
}
}
Here is my PC Server side :
package Server;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
public class SocketServer extends Thread {
final static int _portNumber = 1919; //Arbitrary port number
public static void main(String[] args)
{
try {
new SocketServer().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(_portNumber);
} catch (IOException e) {
System.err.println("Could not listen on port: " + _portNumber);
System.exit(-1);
}
while (listening) {
System.out.println("Huwat huwat kang client..!");
handleClientRequest(serverSocket);
}
serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket;
private PrintWriter _out;
private BufferedReader _in;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
String info;
int maxid;
System.out.println("Client connected to socket: " + _socket.toString());
info = _socket.toString();
//incrementing the msg_id
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
_socket.getOutputStream()));
_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
String inputLine;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/finalclient","root","");
PreparedStatement st = con.prepareStatement("select *from msgs order by msg_id desc");
ResultSet r1 = st.executeQuery();
r1.first(); // or r1.next()
maxid = r1.getInt("msg_id") + 1;
while ((inputLine = _in.readLine()) != null) {
System.out.println("Message from Client: "+inputLine);
out.write(inputLine);
try {
PreparedStatement st1=con.prepareStatement("insert into msgs values(?,?,?)");
st1.setInt(1,maxid);
st1.setString(2,info);
st1.setString(3,inputLine);
int count = st1.executeUpdate ();
System.out.println (count + " rows were inserted to Database");
}
catch (Exception e) {
System.out.println("Failed to Insert from DB"+e);
}
}
}
catch (Exception e) {
System.out.println("Failed to Select from DB"+e);
}
}
}
}

Android. Sockets. Fail Connection

I develop simple client-server app for Android by examples:
http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html
http://android-er.blogspot.com/2014/02/android-sercerclient-example-client.html
Server code:
package com.example.androidserversocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
Client code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I work with TWO emulators Android.
When server starts it gets IP: 10.0.2.15
And in Client window I set IP: 10.0.2.15 and PORT:8080.
But I get exception: "Failed to connect to /10.0.2.15 (port 8080): connect failed: ECONNREFUSED (Connection refused)"
Why I can not connect?
Just to recap this as an answer: Testing on a real device should solve the issue. Apps generally have to be tested on at least one (better several) real device. Especially trying to connect an emulator to another emulator on the same PC is not even remotely close to a real situation. One device would be enough for you. That is, a real Android can connect to an emulator or the other way round as long as the PC allows the connection.

Categories