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

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());

Related

How to get arraylist from java to android

I'm doing an application and I need to receive an udp array from java to android and put it in a Spinner. Does anyone know how to do it?
Now, this is the code that I'm working with but I only receive a string.
Does anyone have an idea of ​​how I can receive the array working from this code?
UDPClientSocketActivity
public class UDPClientSocketActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String message) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
String stringData;
#Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
// IP Address below is the IP address of that Device where server socket is opened.
InetAddress serverAddr = InetAddress.getByName("xxx.xxx.xxx.xxx");
DatagramPacket dp;
dp = new DatagramPacket(message.getBytes(), message.length(), serverAddr, 9001);
ds.send(dp);
byte[] lMsg = new byte[1000];
dp = new DatagramPacket(lMsg, lMsg.length);
ds.receive(dp);
stringData = new String(lMsg, 0, dp.getLength());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
handler.post(new Runnable() {
#Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (stringData.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + stringData);
}
});
}
});
thread.start();
}
}
If you want to put data into Spinner there is a link: https://developer.android.com/guide/topics/ui/controls/spinner

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.

Sockets, sent pdf file always arrives zero bytes size

I'm sending a pdf file from android tablet client to Java app running on Windows 7. The file always arrives as a size of zero bytes. what is the problem here?
Before the pdf file was sent from client to server, the size of the file as long value is sent from client to server, this size is correct and always arrives to the server. For the pdf file, I'm using for this test the size is 566718 bytes.
How can I get the pdf file to arrive as the correct size?
Server code
public class Server {
ServerSocket serverSocket;
Socket socket;
boolean runner = true;
Server() throws IOException{
serverRunner();
System.out.println("server constructor started");
} // Server() constructor
public void serverRunner() throws IOException {
System.out.println("serverrunner started");
try {
serverSocket = new ServerSocket(6789, 100);
runner = true;
while (runner) {
socket = serverSocket.accept();
MultiThreader multi = new MultiThreader(socket);
Thread t = new Thread(multi);
t.start();
} // while runner
} catch (IOException ex) {
}
} // serverRunner()
} // class Server
public class MultiThreader implements Runnable {
Socket socket;
public int fileSizeFromClient;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
DataInputStream dis = null;
DataOutputStream dos = null;
public MultiThreader(Socket socket){
System.out.println("print out from multithreader class");
this.socket = socket;
} // multiThreader
#Override
public void run() {
System.out.println("multi threader started");
// action #1 read file from client =====================================
// transfer.pdf read this file sent from android device to this computer
int bufferSize = 0;
try {
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(bis);
fileSizeFromClient = dis.readInt();
System.out.println("file size from client is " + fileSizeFromClient);
File fileDirectory = new File("C:/DOWNLOAD/");
if (!fileDirectory.exists()) {
fileDirectory.mkdir();
}
File file = new File("C:/DOWNLOAD/transfer.pdf");
file.createNewFile();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
byte[] buffer = new byte[fileSizeFromClient];
int totalBytesRead = 0;
while(totalBytesRead < fileSizeFromClient){
int bytesRemaining = fileSizeFromClient = totalBytesRead;
int bytesRead = dis.read(buffer, 0, (int) Math.min(buffer.length, bytesRemaining));
if(bytesRead == -1) {
break;
} else {
dos.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
} // while
} catch (IOException ex) {
Logger.getLogger(MultiThreader.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// socket.close();
} catch (IOException ex) {
Logger.getLogger(MultiThreader.class.getName()).log(Level.SEVERE, null, ex);
}
}
} // run
} // MultiThreader
client code
public class MainActivity extends Activity implements Runnable {
TextView textViewOne;
Button buttonOne;
Socket socket;
private String serverIP = "192.XXX.X.X";
FileInputStream fis;
FileOutputStream fos;
private File file;
DataInputStream dis;
DataOutputStream dos;
BufferedInputStream bis;
BufferedOutputStream bos;
long length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewOne = (TextView) findViewById(R.id.textView1);
buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread myThread = new Thread(MainActivity.this);
myThread.start();
}
});
} // oncreate
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
textViewOne.setText("run method started");
}
});
try {
socket = new Socket(InetAddress.getByName(serverIP), 6789);
if (socket == null) {
return;
} else {
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
textViewOne.setText("connected");
}
});
}
file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "transfer.pdf");
length = file.length();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(bos);
dos.writeInt((int) length); // sends the length as number bytes is file size
int count = 0;
byte[] buffer = new byte[(int) length];
while ((count = bis.read(buffer)) > 0)
{
bos.write(buffer, 0, count);
}
bos.flush();
bis.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // mainactivity
This is the problem, I believe.
int bytesRemaining = fileSizeFromClient = totalBytesRead;
That's doing two assignments, so you're assigning 0 to fileSizeFromClient immediately, and exiting the loop.
You meant:
int bytesRemaining = fileSizeFromClient - totalBytesRead;
That's a pretty subtle typo, and you were unlucky that it's a typo which still resulted in valid code :(
Given that you're closing the socket immediately anyway though, it's not clear why you're sending the file size first. Your code could be simpler if you just had the same "copy from an input stream to an output stream until the input runs out of data" at both the client and the server, just from a FileInputStream to a Socket's OutputStream at the client, and the Socket's InputStream to a FileOutputStream (possibly with a buffering wrapper) at the server.
I'd also recommend closing all streams - if you're using Java 7, you can do this simply using a try-with-resources statement; in earlier versions you should close streams in finally blocks.
- By rule of thumb, always close the Streams after writing/reading to and from it.
- Close the Stream at Server side.
- Use Socket with InputStream and Scanner for hassle free data transfer between socket. (Thats what i felt, experimenting with sockets.)

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());
}
}
}

Socket - Address already in use

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.

Categories

Resources