serversocket under android

  • Replies:0
chris lee
  • Forum posts: 1

Jul 29, 2013, 1:27:24 PM via Website

Hi, im looking for an example of a Serversocket being used in a bi-directional fashion.
I am writing a 2 part robot control app and need the server app to both receive commands and send binary data back to the client.
So far i have tried the followinf but get FC's when i close the socket.

any help appreciated:

1======CommsThread.java======
2
3package com.example.myserverbot;
4
5/**
6 * Created by chris on 29/07/13.
7 */
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.OutputStream;
11import java.net.Socket;
12
13import android.content.Context;
14import android.os.Handler;
15import android.os.PowerManager;
16import android.util.Log;
17public class CommsThread extends Thread{
18 private final Socket socket;
19 private final InputStream inputStream;
20 private final OutputStream outputStream;
21
22 public CommsThread(Socket sock){
23 socket = sock;
24 InputStream tmpIn = null;
25 OutputStream tmpOut = null;
26 try{
27 tmpIn = socket.getInputStream();
28 tmpOut = socket.getOutputStream();
29 }catch(IOException e){
30 Log.d("SocketChat", e.getLocalizedMessage());
31 }
32 inputStream = tmpIn;
33 outputStream = tmpOut;
34 }
35
36 public void run(){
37 //--buffer store
38 byte[] buffer = new byte[1024];
39 //---number of bytes read
40 int bytes;
41 //---keep listening until exception occurs
42
43
44 while (true){
45 try{
46 //read from input stream
47 bytes = inputStream.read(buffer);
48 //update main UI
49 MainSvrActivity.UIUpdater.obtainMessage(0,bytes, -1, buffer).sendToTarget();
50
51 }catch (IOException e){
52 break;
53 }
54 }
55 }
56 //call this to send data from main UI
57 public void write(byte[] bytes){
58 try{
59 outputStream.write(bytes);
60 }catch(IOException e){
61
62 }
63 }
64
65 public void cancel(){
66 try{
67 socket.close();
68 }catch (IOException e){
69
70 }
71 }
72}
73
74=====Server app ========
75
76package com.example.myserverbot;
77
78import android.content.Context;
79import android.os.AsyncTask;
80import android.os.Bundle;
81import android.app.Activity;
82import android.os.Handler;
83import android.os.Message;
84import android.os.PowerManager;
85import android.util.Log;
86import android.view.Menu;
87import android.view.View;
88import android.widget.Button;
89import android.widget.EditText;
90import android.widget.ImageView;
91
92import java.io.IOException;
93import java.net.InetAddress;
94import java.net.ServerSocket;
95import java.net.Socket;
96import java.net.UnknownHostException;
97
98public class MainSvrActivity extends Activity {
99 String strRecieved;
100 static EditText editText;
101 EditText editText2;
102 ImageView imageView, imageView2, imageView3, imageView4, imageView5;
103 Button button;
104 Button button2;
105 InetAddress serverAddress;
106 Socket socket;
107 CommsThread commsThread;
108 ServerSocket serverSocket;
109 private PowerManager.WakeLock wakeLock;
110 boolean listen4Connection = false;
111 @Override
112 protected void onCreate(Bundle savedInstanceState) {
113 super.onCreate(savedInstanceState);
114 setContentView(R.layout.activity_main);
115 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
116 wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,"dont'tdimscreen");
117 editText = (EditText) findViewById(R.id.editText);
118 editText2 = (EditText) findViewById(R.id.editText2);
119 imageView = (ImageView) findViewById(R.id.imageView);
120 imageView2 = (ImageView) findViewById(R.id.imageView2);
121 imageView3 = (ImageView) findViewById(R.id.imageView3);
122 imageView4 = (ImageView) findViewById(R.id.imageView4);
123 imageView5 = (ImageView) findViewById(R.id.imageView5);
124 button = (Button) findViewById(R.id.button);
125 button.setOnClickListener(new View.OnClickListener() {
126 @Override
127 public void onClick(View view) {
128 listen4Connection = true;
129 new CreateCommThreadTask().execute();
130 }
131 });
132 button2 = (Button) findViewById(R.id.button2);
133 button2.setOnClickListener(new View.OnClickListener() {
134 @Override
135 public void onClick(View view) {
136 listen4Connection = false;
137 new CloseSocketTask().execute();
138 }
139 });
140
141 }
142
143
144 @Override
145 public boolean onCreateOptionsMenu(Menu menu) {
146 // Inflate the menu; this adds items to the action bar if it is present.
147 getMenuInflater().inflate(R.menu.main_svr, menu);
148 return true;
149 }
150 /*
151 statusView.setText(statusView.getText().toString()+ '\n' + "Received from svr:" + strRecieved );
152 if (statusView.getLineCount()==5||statusView.getLineCount()>7)
153 {
154 statusView.scrollBy(0,10);
155 }
156
157
158 */
159 static Handler UIUpdater = new Handler() {
160 @Override
161 public void handleMessage(Message msg){
162 int numOfBytesReceived = msg.arg1;
163 byte[] buffer = (byte[]) msg.obj;
164 String strRecieved = new String(buffer);
165 strRecieved = strRecieved.substring(0,numOfBytesReceived);
166 // LogWindow(strRecieved);
167 editText.setText(editText.getText().toString()+ '\n' + "Received from svr:" + strRecieved );
168 if (editText.getLineCount()==5||editText.getLineCount()>7)
169 {
170 editText.scrollBy(0,10);
171 }
172 }
173
174 };
175 private class CreateCommThreadTask extends AsyncTask<Void, Integer, Void>{
176 @Override
177 protected Void doInBackground(Void... params){
178 try{
179 serverSocket = new ServerSocket(500);
180 socket = serverSocket.accept();
181 commsThread = new CommsThread(socket);
182 commsThread.start();
183 imageView2.setImageResource(R.drawable.green_led);
184 sendToServer("Handshake");
185 }catch(UnknownHostException e){
186 Log.d("Sockets", e.getLocalizedMessage());
187 }catch (IOException e){
188 Log.d("Sockets", e.getLocalizedMessage());
189 }catch (NumberFormatException nfe){
190 Log.d("Sockets", nfe.getLocalizedMessage());
191 }
192 return null;
193 }
194 }
195 private class WriteToServerTask extends AsyncTask<byte[], Void, Void>{
196 protected Void doInBackground(byte[]...data){
197 commsThread.write(data[0]);
198 return null;
199 }
200 }
201
202 private class CloseSocketTask extends AsyncTask<Void, Void, Void>{
203 @Override
204 protected Void doInBackground(Void... params){
205 try{
206 socket.close();
207 imageView2.setImageResource(R.drawable.red_led);
208 }catch (IOException e){
209 Log.d("Sockets", e.getLocalizedMessage());
210 }
211 return null;
212 }
213 }
214
215 private void sendToServer(String message){
216 byte[] theByteArray = message.getBytes();
217 new WriteToServerTask().execute(theByteArray);
218 }
219 @Override
220 protected void onPause() {
221 super.onPause();
222 if (listen4Connection==true){new CloseSocketTask().execute();}
223 wakeLock.release();
224 }//End of onPause
225
226 @Override
227 protected void onResume() {
228 super.onResume();
229 if (listen4Connection==true){new CreateCommThreadTask().execute();}
230 wakeLock.acquire();
231 }//End of onResume
232}

Reply