Hi there im very new to java programing and am really stuck getting a socket server and client working how i want.
The problem im having is...
server:
Im looking at the output from the client and once client prints "TIME" the server will return a message eg "the time is...". The server does this but not straight away it seems to send it on the second time you send a message from the client.
Is this becuase the client is not connected all the time maybe ?
Im pretty sure this method is wrong can anyone give me some advice.
Any help would be great .
Luke
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
try{
String line = in.readLine();
if (line.contains("TIME")){
dataOutputStream.writeUTF("TIME IS....."); // ITS HERE THE PROBLEM MAY BE ?
{
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
} 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( dataInputStream!= null){
try {
dataInputStream.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();
}
}
}
}
}
}
The Android Client
UPDATE , i think the problem is with the client only being connected when you send a message. How do i have a reading loop in here that wont affect when i send data out from the client.
package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} 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();
}
}
}
}};
}
After the dataOutputStream.writeUTF() line, write dataOutputStream.flush();. That will send all the data through.
It seems you’re reading from the stream to output the message.
System.out.println("message: " + dataInputStream.readUTF());
So the command has been removed from the stream when you try to run
String line = in.readLine();
You should try to read the command from the stream into a variable before outputting the message and then check if that string contains "TIME".
Also why use two different methods to read from the stream? You could just use the BufferedReader and discard DataInputStream. You could as well use PrintWriter instead of DataOutputStream.
Something like this:
out = new PrintWriter( socket.getOutputStream(), true );
and then:
out.println( "Time is..." );
Hope this helps.
Related
I have the following code in JAVA to create Server Socket to listen for incoming connections :
public class ConnectOracle {
public static void main(String[] args) {
String driver = "oracle.jdbc.driver.OracleDriver"; //
String serverName = "10.11.201.84";
String portNumber = "1521";
String db = "XE";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":"
+ db; // connectOracle is the data
// source name
String user = "ORAP"; // username of oracle database
String pwd = "ORAP"; // password of oracle database
Connection con = null;
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
Class.forName(driver);// for loading the jdbc driver
System.out.println("JDBC Driver loaded");
con = DriverManager.getConnection(url, user, pwd);// for
// establishing
// connection
// with database
Statement stmt = (Statement) con.createStatement();
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
while (true) {
try {
socket = serverSocket.accept();
System.out.println("Connection Created");
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
// System.out.println("message: " +
// dataInputStream.readUTF());
ResultSet res=stmt.executeQuery("select * from food_category");
while(res.next()){
System.out.println(res.getString(1));
}
} 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();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In my Android program I am trying to create a connection with this JAVA program . The code is as follows :
class ConnectToOracle extends AsyncTask<String, String, String> {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
;
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
try {
socket = new Socket("10.11.201.84", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} 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;
}
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
// Dismiss the dialog after the Music file was downloaded
}
}
But the connection is not established . How can I establish connection ? Any advice is of great help .
I have established a connection between java server and android client using sockets. I can send messages from android to java, but only 1 message at a time.
what if I want to send data of 2 variables from android to java and at the same time receive those data in java in 2 different variables.
How can I achieve this.??
Code for Android Client
public class MessageClient extends Activity implements OnClickListener {
EditText etMessage;
Button bSend;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messageclient);
bSend = (Button) findViewById(R.id.button1);
etMessage = (EditText) findViewById(R.id.etMessage);
bSend.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try {
Socket s = new Socket("192.168.0.100",7000);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(etMessage.getText().toString());
dos.flush();
dos.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Code for java server
public static void main(String arg[]){
Thread t = new Thread(){
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket ss = new ServerSocket(7000);
while(true){
Socket s = ss.accept();
System.out.println("Server is running");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Received from client: "+dis.readUTF());
dis.close();
s.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
Thank you.
You are just sending a String and then closing the socket.You can try to send lists and also can send multiple DataInputStream dis without closing the socket connection.
I have a problem, and I don´t know if it´s possible.
I have an Android app that are a client socket.
This is the code to send a message to a server in Android App:
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
System.out.println("envia mensaje");
client = new Socket("ip of server", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // 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;
}
}
At same time, in Android App, a socket is created in 4445 port:
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4445;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println(message);
}
});
/*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();*/
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the server code, that create a socket in 4444 port:
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println("Dirección entrante"+clientSocket.getInetAddress());
//System.out.println("Dirección entrante2"+clientSocket.get());
System.out.println(message);
ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length());
//message.substring(message.indexOf(":")+1, message.length()).trim();
System.out.println("realiza conexión a ip:#"+ip_a+"#");
messsage = "enviado desde el servidor"; // get the text message on the text field
SendMessage(ip_a);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
This work correctly, but I want send a message from server to a Android device throug IP that socket have.
I try with clientSocket.getInetAddress(), and with clientSocket.getRemoteSocketAddress(), but not work. I create a socket in Android app in 4445 port, but the server can´t connect to socket of android app.
Can you help me?
Thanks in advance
Ok, I will try.
This is my server aplication:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class SimpleTextServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static Socket client;
private static String messsage;
private static PrintWriter printwriter;
static String ip_a;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
System.out.println("Server started. Listening to the port 4444:"+getIpAddress());
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println("Dirección entrante"+clientSocket.getInetAddress());
//System.out.println("Dirección entrante2"+clientSocket.get());
System.out.println(message);
ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length());
//message.substring(message.indexOf(":")+1, message.length()).trim();
System.out.println("realiza conexión a ip:#"+ip_a+"#");
messsage = "enviado desde el servidor"; // get the text message on the text field
SendMessage(ip_a);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
public static void SendMessage(String ip) {
try {
System.out.println("comienza a enviar mensaje");
client = new Socket(ip, 4445); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // 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();
}
}
public static 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;
}
}
And this is my activity in my Android app:
package com.lakj.comspace.simpletextclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SlimpleTextClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
//ServerSocket serverSocket;
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
System.out.println("IP DE CLIENTE EMULADOR: "+getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
//myClientTask.execute();
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("ENVIA MENSAJE BOTON");
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
System.out.println("envia mensaje");
client = new Socket("ip de servidor", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // 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;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slimple_text_client, menu);
return true;
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4445;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println(message);
}
});
/*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();*/
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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;
}
}
If I run the android app, the message is sended to server, and server show it.
But, the server can´t connect to Android. The IP is unracheable. I don´t know why...
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Im' writing a sample chat program that sends message between 2 android phones, so I wrote the following and let a phone connect to itself(10.0.2.2 or localhost) to test it the code works or not.
But looks like in the thread of receivemsg(), the socket is never connected. So did I use the wrong ip address to refer to myself? or does my code have something wrong? thank you for your help!
package com.example.chatroomprogram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ClientActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
public String ipaddress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
Intent intent = getIntent();
ipaddress=intent.getStringExtra("ipaddress");
Log.i("123","ip is "+ipaddress);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
//msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
// receiveMsg();
//----------------------------
//server msg receieve
//-----------------------
//End Receive msg from server//
}
public void sendMessageToServer(String str) {
final String str1=str;
new Thread(new Runnable() {
#Override
public void run() {
//String host = "opuntia.cs.utep.edu";
//String host="10.0.";
String host2 = "10.0.2.2";
PrintWriter out = null;
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("123","not null");
// out.println("hello");
out.println(str1);
Log.i("123", "hello");
out.flush();
}
}).start();
}
public void receiveMsg()
{
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
//final String host="opuntia.cs.utep.edu";
final String host="10.0.2.2";
//final String host="127.0.0.1";
Socket socket = null ;
BufferedReader in = null;
try {
//socket = new Socket(host,8008);
ServerSocket ss = new ServerSocket(8008);
socket = ss.accept();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
String msg = null;
try {
msg = in.readLine();
Log.i("123","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(msg == null)
{
break;
}
else
{
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg)
{
final String mssg=msg;
handler.post(new Runnable() {
#SuppressLint("NewApi")
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.i("123","hi");
}
});
}
}
update: Problem solved, conclusion: if you use AVD, just use 10.0.2.2; if you use an actual phone to debug, you can use localhost
my bad... i used 10.0.2.2 and it works...
i got this code form Android-er blogspot, big thanks for him to make me almost understand basic socket connections in java. So i got this client app on my android device, and computer with server running, but how could i make a loop in a client code, to make it send data from EditText in real time? (whenever it changes) Please if someone could clear it out for a complete newbie?
-----This is client code (Android-er Copyrights):
package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} 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();
}
}
}
}};
}
-----This is server code (Android-er Copyrights):
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} 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( dataInputStream!= null){
try {
dataInputStream.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();
}
}
}
}
}
}
There are a few things you will need to change.
First of all, if you want the data to be sent in real time, you will need to change from using a Button OnClickListener to using a TextWatcher (see addTextChangedListener in TextView)
As this event will be fired every time the text changes, you will need to open your socket outside of the event (you don't want a new socket each time some text is typed), and then in your listener, you just want to send the new data down the socket.
You can set a text changed listener on your EditText and do the sending from there.
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// ... do your sending here
}
But beware that if that sending is not asynchronous, it may block text entry for the user. Network latency can be relatively high on GSM networks, so the user may be irritated, when his freshly typed characters will not immediately appear on screen.