Socket - Address already in use - java

I'm new to Socketand I try to code an Server and Client on the same application just to see how it work.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)this.findViewById(R.id.bouton1)).setOnClickListener(this);
}
public void onClick(View v) {
TCPServer server = new TCPServer();
TCPClient client = new TCPClient();
server.start();
client.start();
}
public class TCPServer extends Thread {
#Override public void run() {
try {
ServerSocket s = new ServerSocket(8080,0,InetAddress.getLocalHost());
Socket cli = s.accept();
byte[] b = new byte[512];
int n;
InputStream is = cli.getInputStream();
while((n=is.read(b))>0){
Log.d("TCPServer",new String(b));
if(new String(b).contains("\r\n\r\n"))break;
b = new byte[512];
}
OutputStream os = cli.getOutputStream();
os.write("Hello".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TCPClient extends Thread {
#Override public void run() {
try {
Socket s = new Socket(InetAddress.getLocalHost().getHostAddress(),8080);
//Socket s = new Socket("www.google.com",80);
//Log.i("",s.getLocalAddress().getHostAddress());
byte[] b = new byte[512];
int n;
if (s.isConnected()) {
OutputStream os = s.getOutputStream();
os.write("Hi How are you \r\n\r\n".getBytes());
InputStream is = s.getInputStream();
while((n=is.read(b))>0){
Log.d("TCPClient",new String(b));
b = new byte[512];
}
}
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The code work fine but just for the first time I click my button.
the error is java.net.BindException: Address already in use .

If it works the first time, but not after that it sounds like you aren't closing your socket correctly before your program exits.
You can check to see if it's still open by running
netstat
pending your not on a windows machine. I'm sure they have something similar.

Related

Android SDK, Output Stream from client to server doesn't work

So I was just seeing if I could build a dead simple chat application, and im facing a problem... I have the server running on my pc and the client on my phone, Once the client has connected to my pc I can then go to my pc and write as many messages as I want and they will appear on my phone (client), but when I try to send a message from my phone it will only send one message then no more, any ideas?
Server:
static OutputStream out;
static InputStream in;
String name = "Server";
public static void main(String args[]){
System.out.println("Server On");
//Server
new Thread(new Runnable(){
#Override
public void run(){
new Main().start();
}}).start();
//Scanner for text input
new Main().scrnn();
}
public void scrnn(){
Scanner lol = new Scanner(System.in);
if(lol.hasNext()){
try {
out.write((name + ": " +lol.nextLine().toString()).getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
scrnn();
}
public void start(){
try{
ServerSocket sok = new ServerSocket(42069);
while(true){
Socket sk = sok.accept();
in = sk.getInputStream();
out = sk.getOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer);
String recievedData = new String(buffer);
System.out.println(recievedData);
out.write(recievedData.getBytes());
}
}catch(Exception e){
e.printStackTrace();
}
}
And the client:(android phone)
OutputStream out;
InputStream in;
Socket sk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new Object[]{"Thanks for using Monsterchat"};
Button button = (Button)findViewById(R.id.buttonSend);
listView = (ListView) findViewById(R.id.listView);
new Thread(new Runnable() {
#Override
public void run() {
try {
sk = new Socket("10.0.0.9", 42069);
sk.setKeepAlive(true);
out = sk.getOutputStream();
in = sk.getInputStream();
//This will send fine but if you look at the button onclick it wont send that :(
out.write((name + " Joined the group!").getBytes());
//This is how i can send constant messages from the server though
listenForData();
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
try {
out.write("succ".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
}
public void listenForData() throws Exception{
byte[] buffer = new byte[1024];
in.read(buffer);
final String recievedData = new String(buffer);
runOnUiThread(new Runnable() {
#Override
public void run() {
//Update listView with new message
buildList(recievedData);
}
});
//Repeat
listenForData();
}
Sorry there's a lot of code, and also nothing gets output in the logcat that looks wrong
while(true){
Socket sk = sok.accept();
in = sk.getInputStream();
out = sk.getOutputStream();
Dr byte[] buffer = new byte[1024];
in.read(buffer);
String recievedData = new String(buffer);
System.out.println(recievedData);
out.write(recievedData.getBytes());
That loop is wrong. After one received message the server drops sk and will go waiting for a new client.
You better try;
Socket sk = sok.accept();
in = sk.getInputStream();
out = sk.getOutputStream();
byte[] buffer = new byte[1024];
while(true){
int nread = in.read(buffer);
String recievedData = new String(buffer, 0, nread);
System.out.println(recievedData);
out.write(recievedData.getBytes());

Android 2-Way TCP/IP ServerSocket/Socket Communication

Using this great tutorial by the Java Code Geeks, I am easily able to create a client activity that sends data via TCP to a server's port 4000 using the following code:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
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);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Then using their other snippet for the server activity I can catch messages using TCP on that port:
public class Server extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
My question is how can I make it so these 2 can communicate back and forth?
Android -> Server(4000) -> Android(4001)?
In other words how can I make my app help the device act as both the client (sending out data to another device on port 4000) and the server (listening for data on port 4001) at the same time?
On the Server side change the port to 5000 (same as Client) instead of 6000:
And you need to update the following class because you don't want to create a new socket, you should use the one already created (in the Client part).
NB: the socket given as an argument to CommunicationThread is the socket that you supposedly already created (Client part).
class ServerThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
}
}

How to accept multiple socket connection at Java server

I'm trying to implement a client-server pair in Android using standard Java sockets. So far, I've successfully implemented one to one client-server connection. Now, I'm modifying my server side code to accept multiple client connection. I've taken help from here. I'm creating a serverSocket and wait for client connection in an infinite while loop. Once the client side socked is accepted, I run a new thread to handle that client and then again wait for new connection. Unfortunately, the program keeps crashing for some unknown reason! The logcat simply says- "error opening trace file: No such file or directory". The file path is correct (it was working fine in older implementation). Can anyone suggest what am I doing wrong? Is it related to missing manifest permission? Here is what I've done so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent launchFileManager = new Intent(getBaseContext(),
FileChooserActivity.class);
startActivityForResult(launchFileManager, REQUEST_CODE); //receives files
//fileArray has been populated here
Button btn=(Button)findViewById(R.id.dispFilesid);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initializeServer();
}
});
}
private void initializeServer() {
boolean listening = true;
try {
serversocket = new ServerSocket(4444);
} catch (IOException e) {
e.printStackTrace();
Log.d("Listen failed", "Listening to port 4444 failed");
}
while (listening) {
try {
socket = serversocket.accept();
Thread Clienttrd = new Thread(new Runnable() {
#Override
public void run() {
try {
OutputStream myos=socket.getOutputStream();
myos.write(filepathNameArray.size()); //send file count
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!fileArray.isEmpty()) {
for (int i = 0; i < filepathNameArray.size(); i++){
copyFile(fileArray.get(i), fileArray.get(i).getName().toString());
//mtv.setText(fileArray.get(i).getName().toString());
}
}
}
});
Clienttrd.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The intent for FileChooserActivity returns an ArrayList containing a list of file URIs. These URIs are then wrapped around files and written over DataOutputStream of Socket object.
Please help. Any insight would be appreciated! Thanks in advance!
Finally solved the problem. This might help others who land on this page in future. The problem: I was using the same thread for accepting and handling the client connection. So, the server could not become free for listening other incoming connections. I wrote a separate ConnectionHandler class for handling client connection:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
try {
serversocket = new ServerSocket(4444);
} catch (IOException e) {
e.printStackTrace();
Log.d("Listen failed",
"Listening to port 4444 failed");
}
while (listening) {
try {
socket = serversocket.accept();
Runnable connectionHandler = new ConnectionHandler(
socket, fileArray, filepathNameArray);
new Thread(connectionHandler).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
trd.start();
}
});
ConnectionHandler (This solved my issue):
public class ConnectionHandler implements Runnable {
private Socket socket=null;
private ArrayList<File> fileArray=null;
ArrayList<String> filepathNameArray=null;
public ConnectionHandler(Socket socket, ArrayList<File> fileArray, ArrayList<String> filepathNameArray) {
super();
this.socket = socket;
this.fileArray=fileArray;
this.filepathNameArray=filepathNameArray;
}
#Override
public void run() {
try {
OutputStream myos=socket.getOutputStream();
myos.write(filepathNameArray.size()); //send file count
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!fileArray.isEmpty()) {
for (int i = 0; i < filepathNameArray.size(); i++){
copyFile(fileArray.get(i), fileArray.get(i).getName().toString());
//mtv.setText(fileArray.get(i).getName().toString());
}
}
}
private void copyFile(File file, String name) {
FileInputStream fis;
long filesize = file.length();
try {
fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
#SuppressWarnings("resource")
DataInputStream dis = new DataInputStream(bis);
byte[] mybytearray = new byte[16384];
OutputStream os;
if (socket != null) {
os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(name); // filename is also sent to client
dos.writeLong(filesize); // file size is also sent to client
long z = filesize;
int n = 0;
while ((z > 0)
&& (n = dis.read(mybytearray, 0,
(int) Math.min(mybytearray.length, z))) != -1) {
dos.write(mybytearray, 0, n);
dos.flush();
z -= n;
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Why are my client threads/listeners not receiving broadcasted messages from the server?

I made a simple prototype of a client-server application on Android
I managed to connect two clients to the server and the server can receive their messages. The problem now is that I can't seem to broadcast/receive the messages to other clients.
I try to broadcast the received message through a for loop in the Server class:
private void broadcastMessage(String message) {
for (int i = 0, j = clients.size(); i <= j; i++) {
PrintWriter out = null;
Socket socket = clients.get(i);
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// WHERE YOU ISSUE THE COMMANDS
out.println(message);
Log.d("SERVER Loop", "Broadcasting messages...");
out.close();
}
Log.d("SERVER", "Message Brodcasted");
}
This I then try to receive through a listener in the Client class :
public class ClientThreadListener implements Runnable {
protected Socket serverSocket = null;
protected String mMsgFromServer;
public ClientThreadListener(Socket serverSocket) {
this.serverSocket = serverSocket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
serverSocket.getInputStream()));
while ((mMsgFromServer = in.readLine()) != null) {
Log.d("MESSAGE FROM SERVER: ", mMsgFromServer);
handler.post(new Runnable() {
#Override
public void run() {
msgFromOtherClients.append('\n'
+ "Message From Server: " + mMsgFromServer);
}
});
}
} catch (Exception e) {
Log.e("ClientListener", "C: Error", e);
connected = false;
}
}
}
I don't get any errors or force closes though. Forgive me I know it is very messy but please bear with me and please focus on the issue at hand instead :D
Here is the full code for the Server class
public class Server extends Activity {
private TextView serverStatus;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
private String mMsgFromClient;
private MultiThreadedServer server;
private ArrayList<Socket> clients = new ArrayList<Socket>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
// SERVERIP = getLocalIpAddress();
server = new MultiThreadedServer(8080);
new Thread(server).start();
}
public class MultiThreadedServer implements Runnable {
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread = null;
public MultiThreadedServer(int port) {
this.serverPort = port;
}
public void run() {
synchronized (this) {
this.runningThread = Thread.currentThread();
}
openServerSocket();
while (!isStopped()) {
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
clients.add(clientSocket);
} catch (IOException e) {
if (isStopped()) {
Log.d("SERVER TEXT", "Server Stopped.");
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
new Thread(new WorkerRunnable(clientSocket, this)).start();
}
Log.d("SERVER TEXT", "Server Stopped.");
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
private void broadcastMessage(String message) {
for (int i = 0, j = clients.size(); i <= j; i++) {
PrintWriter out = null;
Socket socket = clients.get(i);
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// WHERE YOU ISSUE THE COMMANDS
out.println(message);
Log.d("SERVER Loop", "Broadcasting messages...");
out.close();
}
Log.d("SERVER", "Message Brodcasted");
}
}
public class WorkerRunnable implements Runnable {
protected Socket clientSocket = null;
protected String mMsgFromClient = null;
private UUID id;
public WorkerRunnable(Socket clientSocket, MultiThreadedServer server) {
this.clientSocket = clientSocket;
id = UUID.randomUUID();
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((mMsgFromClient = in.readLine()) != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.append('\n'
+ "Message From Client ID " + getID()
+ ": " + mMsgFromClient);
}
});
}
Log.d("SERVERTEXT", "Proceed to broadcast");
server.broadcastMessage(mMsgFromClient);
} catch (IOException e) {
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus
.append('\n'
+ "Message From Client ID "
+ getID()
+ ": "
+ "Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
private String getID() {
return id.toString();
}
}
}
Here is the full code for the Client class
public class Client extends Activity {
private EditText serverIp;
private EditText chatMsg;
private Button connectPhones;
private Button sendMsg;
private TextView msgFromOtherClients;
private String serverIpAddress = "";
private boolean connected = false;
private boolean willSendMsg = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
chatMsg = (EditText) findViewById(R.id.chat_msg);
sendMsg = (Button) findViewById(R.id.send_msg);
sendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
willSendMsg = true;
}
});
msgFromOtherClients = (TextView) findViewById(R.id.msg_from_other_clients);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, Server.SERVERPORT);
connected = true;
Thread listener = new Thread(new ClientThreadListener(new Socket(serverAddr, Server.SERVERPORT)));
listener.start();
while (connected) {
if (willSendMsg) {
willSendMsg = false;
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
out.println(chatMsg.getText().toString());
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
public class ClientThreadListener implements Runnable {
protected Socket serverSocket = null;
protected String mMsgFromServer;
public ClientThreadListener(Socket serverSocket) {
this.serverSocket = serverSocket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
serverSocket.getInputStream()));
while ((mMsgFromServer = in.readLine()) != null) {
Log.d("MESSAGE FROM SERVER: ", mMsgFromServer);
handler.post(new Runnable() {
#Override
public void run() {
msgFromOtherClients.append('\n'
+ "Message From Server: " + mMsgFromServer);
}
});
}
} catch (Exception e) {
Log.e("ClientListener", "C: Error", e);
connected = false;
}
}
}
}
Your code has some issue that prevents it from working.
As already said in other answers, in your code you are closing the socket output stream right after sending the message to the client. call close() only out of your for message loop. Of course closing the socket in the client will have the same effect as closing it on the server. You must close the sockets only when client and server have finished talking. Closing it while transmitting data it's like hanging up the phone in the middle of a conversation.
Second, you create a new socket on the client side:
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, Server.SERVERPORT);
but then you pass to the listener another, newly created, socket (I suppose this is not intended):
connected = true;
Thread listener = new Thread(new ClientThreadListener(new Socket(serverAddr, Server.SERVERPORT)));
listener.start();
Third, always call flush() on an output stream right after sending data, or the data will likely not be sent (the send methods will just enqueue your data in the sending buffer).
Last (This may not be useful to you since I don't know your ultimate goal), if you need to send and receive on sockets, 90% of the time it's better and easier to do this asinchronously, using separate threads for listening and sending.
If it still doesn't work, add here some output or log trace from logcat.
You need to move the line:
server.broadcastMessage(mMsgFromClient);
inside the while:
while ((mMsgFromClient = in.readLine()) != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.append('\n'
+ "Message From Client ID " + getID()
+ ": " + mMsgFromClient);
}
});
// HERE
Log.d("SERVERTEXT", "Proceed to broadcast");
server.broadcastMessage(mMsgFromClient);
}
Otherwise, you'll only broadcast null.
EDIT: You should make sure that mMsgFromClient is not changed between posting the new Runnable and it actually executing. The best way is to initialize a field in the anonymous class with the current value, and log the value of that field instead.
EDIT2: Unless your server is supposed to close its connection to a client after sending it a broadcast message, you should use out.flush() instead of out.close() in the broadcastMessage method. It's preferrable that client connections are closed after a timeout, or just let the clients disconnect, again with a timeout.
Otherwise, your test will be very limited most of the times: a client connects and sends a message; then it receives its own message and the server closes the connection.
Please try to use AsyncTask in android which will create separate thread for communication with server.

Socket can be send only once and the Textview is not gathering the information from the server

I had two issues in the program I am making... the thing is that I want to send by a Edittext that information to a server via UDP....the thing is that the program only works the first time I run the program, I mean, if i open the application and write some text, the information is sended to the server, but if I type another thing and press to button so the new information is sended it doesn't work... the other thing is that the TextView is not appending the information, and the server send some info but the application is not gathering that information... so if someone had a clue why is this happening or what I am doing wrong I appreciated any help!... Thanks in advice...
here is the code:
public class MainActivity extends Activity implements View.OnClickListener {
public static final String SERVERIP = "190.99.20.200";
public static final int SERVERPORT = 5153;
public TextView serverResponse;
public EditText messageToSend;
public Button btnSend;
public boolean start;
public Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverResponse = (TextView)findViewById(R.id.textView);
messageToSend = (EditText)findViewById(R.id.editText);
btnSend = (Button)findViewById(R.id.button);
btnSend.setOnClickListener(this);
start = false;
new Thread(new Server()).start();
try{
Thread.sleep(500);
}catch (InterruptedException e){
updatetrack("Error on Server:" + e.getMessage());
}
new Thread(new Client()).start();
handler = new Handler(){
public void handledMessage(Message msg){
String text = (String)msg.obj;
serverResponse.append(text);
}
};
}
public class Client implements Runnable {
#Override
public void run() {
while(start == false)
{
}
try{
Thread.sleep(500);
}catch (InterruptedException e1){
e1.printStackTrace();
}
try{
InetAddress serverAddres = InetAddress.getByName(SERVERIP);
updatetrack("Client:Start connectingn");
DatagramSocket socket = new DatagramSocket();
byte[] buffer;
if(!messageToSend.getText().toString().isEmpty())
{
buffer = messageToSend.getText().toString().getBytes();
}
else
{
buffer = ("Message from android").getBytes();
}
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,serverAddres,SERVERPORT);
updatetrack("Client:Sending" + new String(buffer)+ "'n");
socket.send(packet);
updatetrack("Client: Messange sentn");
updatetrack("Client: Succed!n ");
socket.close();
}catch (Exception e){
updatetrack("Client:Error!n" + e.getMessage());
}
}
}
public class Server implements Runnable{
#Override
public void run() {
while (start == false)
{
}
try{
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:" + new String(packet.getData())+"'n");
updatetrack("Server : Succed!n");
}catch (Exception e){
updatetrack("Server: Error!n"+ e.getMessage());
}
}
}
public void onClick(View view)
{
start = true;
}
public void updatetrack(String s)
{
Message msg = new Message();
String textTochange = s;
msg.obj = textTochange;
handler.sendMessage(msg);
}
}
The run method in your server class will run only once.
while(start == false){
}
This while loop will continue to loop until you call the onClick method, at which point the rest of the code in the run() method is executed, and the server thread killed. You need to rearrange your code a little, and place it inside the while loop:
public void run() {
while (true){
try{
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:" + new String(packet.getData())+"'n");
updatetrack("Server : Succed!n");
}catch (Exception e){
updatetrack("Server: Error!n"+ e.getMessage());
}
}
}

Categories

Resources