I need Your help!
So I got this app on an Android device, in which I get data from the accelerometer, and button presses which get this data to an edittext, and sets listeners on the edittextes.
When it's changed, there's a functions that creates a socket, sends data, and closes the socket.
Then I have a server app on my computer, in which I create serversockets, and create two threads that are waiting for serversocket.accept() that gets the data and put it into texbox. Simple as that.
I'm glad that I got it working anyway :-) but the point is, it's not working so well. I believe that whole communication is bad and not optimized. It sends data well, but often freezes, then unfreezes and sends quickly all previous data and so on.
I'm sorry for my bad code, but can someone please take a good look on this, and propose what I should change and how I could make it work more smooth and stable? :-(
Here's the Client code:
package com.test.klienttcp;
//import's...
public class Klient extends Activity implements SensorListener {
final String log = "Log";
EditText textOut;
EditText adres;
EditText test;
EditText gazuje;
TextView textIn;
TextView tekst;
TextView dziala;
String numer = null;
float wspk = 0; // wspolczynniki kalibracji
float wychylenietmp = 0;
float wychylenie = 0;
int tmp = 0;
int i = 0;
boolean wysylaj = false;
SensorManager sm = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
adres = (EditText)findViewById(R.id.adres);
gazuje = (EditText)findViewById(R.id.gazuje);
Button kalibracja = (Button)findViewById(R.id.kalibracja);
Button polacz = (Button)findViewById(R.id.polacz);
Button gaz = (Button)findViewById(R.id.gaz);
Button hamulec = (Button)findViewById(R.id.hamulec);
kalibracja.setOnClickListener(kalibracjaOnClickListener);
polacz.setOnClickListener(polaczOnClickListener);
gaz.setOnTouchListener(gazOnTouchListener);
hamulec.setOnTouchListener(hamulecOnTouchListener);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
//text listener steering
textOut.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Wyslij();
}
}
});
//text listener for throttle
gazuje.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Gaz();
}
}
});
}
Button.OnClickListener polaczOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(wysylaj==false)
{
wysylaj = true;
}
else
{
wysylaj = false;
}
}};
//throttle button handler
Button.OnTouchListener gazOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("1");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//brake button handler
Button.OnTouchListener hamulecOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("2");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//sensor handler
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
wychylenie = values[0] * 10;
tmp = Math.round(wychylenie);
wychylenie = tmp / 10;
if(wychylenie != wychylenietmp)
{
textOut.setText(Float.toString(wychylenie - wspk));
wychylenietmp = wychylenie;
}
}
}
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(log, "onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this, SensorManager.SENSOR_ORIENTATION
| SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
//callibration handler
Button.OnClickListener kalibracjaOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
wspk = wychylenie;
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
// sending steering data
public void Wyslij()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//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();
}
}
}
}
//sending throttle data
public void Gaz()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8889);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(gazuje.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//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();
}
}
}
}
}
And here's Server code:
//import's...
public class Okno
{
public static float wychylenie;
public static String gaz="0";
public static float jedzie;
public static int skrecam, gazuje;
public static String wiadomosc="100";
private static int maxConnections=0, port=8888, portg=8889;
public static void main(String[] args)
{
skrecam = 0;
gazuje = 0;
Window ok = new Window();
ok.setDefaultCloseOperation(3);
ok.setVisible(true);
ok.setResizable(false);
ok.setTitle("Serwer TCP");
int i=0;
try{
Robot robot = new Robot();
Robot robotgaz = new Robot();
ServerSocket listener = new ServerSocket(port);
ServerSocket listenergaz = new ServerSocket(portg);
while((i++ < maxConnections) || (maxConnections == 0)){
//create thread for steering
if(skrecam == 0)
{
skrecam=1;
doComms conn_c= new doComms(listener);
Thread t = new Thread(conn_c);
t.start();
}
//create thread for throttle
if(gazuje == 0)
{
gazuje=1;
doCommsgaz conn_gaz= new doCommsgaz(listenergaz);
Thread tgaz = new Thread(conn_gaz);
tgaz.start();
}
ok.pole3.setText(wiadomosc);
ok.pole2.setText(gaz);
}
}
catch (AWTException e) {
e.printStackTrace();
}
catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doComms(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.wiadomosc = in.readUTF();
server.close();
Okno.skrecam=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doCommsgaz implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doCommsgaz(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.gaz = in.readUTF();
server.close();
Okno.gazuje=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class Window extends JFrame {
private JButton ustaw;
public JTextField pole1;
public JTextField pole2;
public JTextField pole3;
Window()
{
setSize(300,200);
getContentPane().setLayout(new GridLayout(4,1));
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(1));
getContentPane().add(panel1);
pole1 = new JTextField(15);
panel1.add(pole1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(1));
getContentPane().add(panel2);
pole2 = new JTextField(15);
panel2.add(pole2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(1));
getContentPane().add(panel3);
pole3 = new JTextField(15);
panel3.add(pole3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(1));
getContentPane().add(panel4);
ustaw = new JButton("Ustaw");
panel4.add(ustaw);
//action button handler
ustaw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent zdarz){
try{
}
catch(Exception wyjatek){}
pole1.setText("costam");
}
});
}
}
Once again, sorry for the non optimized, and hard-to-read code. But please, if someone knows what would be better, please respond.
Thanks a lot!
The client socket code should go into an AsyncTask. Google has a good into to it here. This will not speed anything up but it will stop your app from freezing. You can put in a "Processing" message while displaying a progress dialog to let the user know that something is happening.
Related
I'm working on a server-client game in which I need to update client's JFrame from the server in a specific period.this is my game
The problem is that the client's JFrame does not update.to be sure,I have rendered the JFrame Submitted by the server and it's OK,but the client's JFrame does not change at all.Here's my code:
my server:
public class main implements java.io.Serializable{
static ArrayList<Socket> allsockets = new ArrayList<>();
static ArrayList<ObjectOutputStream> oos = new ArrayList<>();
static final MainFrame frame=new MainFrame();
static boolean testfirst=false;
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
String color;
Color color1 = null;
Socket clientsocket=null;
ServerSocket serversocket=null;
PrintStream os = null;
ObjectInputStream is=null;
try{
serversocket = new ServerSocket(); // don't bind just yet
serversocket.setReuseAddress(true);
serversocket.bind(new InetSocketAddress(5555)); // can bind with reuse= true
}
catch(IOException e){
System.out.println(e);
}
while(true){
try {
clientsocket=serversocket.accept();
allsockets.add(clientsocket);
oos.add(new ObjectOutputStream(clientsocket.getOutputStream()));
is=new ObjectInputStream(clientsocket.getInputStream());
os = new PrintStream(clientsocket.getOutputStream());
try {
name =(String) is.readObject();
color=(String) is.readObject();
try {
java.lang.reflect.Field field = Class.forName("java.awt.Color").getField(color);
color1 = (Color)field.get(null);
} catch (Exception e) {
color = null;
}
player p=new player();
frame.addplayer(name, color1,p);
if(!testfirst){
testfirst=true;
new Thread(){
public void run(){
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("timer works");
for(ObjectOutputStream os:oos){
try {
os.writeObject(frame);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, 1);
}
}.start();
}
handle h= new handle(is, frame, p);
h.start();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my client:
public class client implements java.io.Serializable {
static private final Lock mutex = new ReentrantLock(true);
private static final long serialVersionUID = 1L;
static double prevx =0;
static double prevy=0;
static Timer timer=new Timer();
static ObjectOutputStream os =null;
public static void main(String[]args) {
MainFrame frame=new MainFrame();
Socket clientSocket=null;
ObjectInputStream is=null;
String name;
String color;
try {
clientSocket = new Socket("localhost", 5555);
os = new ObjectOutputStream(clientSocket.getOutputStream());
is=new ObjectInputStream(clientSocket.getInputStream());
System.out.println("enter your name:");
Scanner in1=new Scanner(System.in);
name=in1.nextLine();
System.out.println("enter your color:");
color=in1.nextLine();
in1.close();
os.writeObject(name);
os.writeObject(color);
refresh ref=new refresh( is, os);
ref.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to host");
}
}}
the refresh class(which has the responsibility to update client's JFrame)
public class refresh extends Thread{
MainFrame frame;
ObjectInputStream ois;
ObjectOutputStream oos;
Timer timer=new Timer();
double prevx,prevy;
private Lock mutex = new ReentrantLock(true);
public refresh(ObjectInputStream ois,ObjectOutputStream oos){
frame=new MainFrame();
this.ois=ois;
this.oos=oos;
}
public void run(){
while(true){
try {
frame= (MainFrame) ois.readObject();
frame.repaint();
frame.removeMouseMotionListener(mml);
frame.addMouseMotionListener(mml);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setFocusable(true);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MouseMotionListener mml=new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
mutex.lock();
try {
System.out.println("mouse moved");
oos.writeObject(arg0.getX());
oos.writeObject(arg0.getY());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mutex.unlock();
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
};}
and if needed the handle class(which receives the mouse coordinates from the client)
public class handle extends Thread{
double prevx,prevy;
MainFrame frame;
player myplayer;
ObjectInputStream ois;
double screenwidth,screenheigth;
boolean first=false;
boolean finished = false;
static private final Lock mutex = new ReentrantLock(true);
Thread movethread = new Thread(){
public void run(){
System.out.println("movethread run");
try {
if(Math.abs(prevx-myplayer.xcenter)>1 || Math.abs(prevy - myplayer.ycenter)>1){
while(Math.abs(prevx-myplayer.xcenter)!=0
|| Math.abs(prevy - myplayer.ycenter)!=0){
if(prevx<0 || prevx>screenwidth || prevy<0 || prevy>screenheigth)break;
myplayer.movem(prevx, prevy,mutex);
frame.repaint();
System.out.println(myplayer.cp.getCenter());
}
finished = true;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public handle(ObjectInputStream ois,MainFrame frame,player p) {
// TODO Auto-generated constructor stub
this.myplayer=p;
this.ois=ois;
this.frame=frame;
this.screenwidth=frame.getscreenwidth();
this.screenheigth=frame.getscreenheigth();
}
public void run(){
System.out.println("handle thread run");
while(true){
try {
System.out.println("in handle");
System.out.println(first);
prevx= (double) ois.readObject();
prevy=(double) ois.readObject();
if(!first){
System.out.println("movethread started");
movethread.start();
first = true;
}
else if(first && finished){
movethread.run();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void update(double x,double y){
this.prevx=x;
this.prevy=y;
}}
Any help would be appreciated.
I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?
I would be really grateful if someone could point me in the right direction
How would i go about triggering an event that is called when no data is received from the serial communication example below?
Thank you,
Maria.
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
theSerialWriter = new SerialWriter(this, out);
new Thread(theSerialWriter).start();
serialPort.addEventListener(new SerialReader(this, in));
serialPort.notifyOnDataAvailable(true);
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public void serialEvent(SerialPortEvent arg0) {
int data;
// boolean setFlagDoorLock = false ;
// if(arg0= 1){}
try {
int len = 0;
while ((data = in.read()) > -1) {
if (data == '\n') {
break;
}
buffer[len++] = (byte) data;
asHexStr = DatatypeConverter.printHexBinary(buffer);
if (asHexStr.contains("FB1")) {
// Thread.sleep(1000);
ActivateSystem = true;
if ((asHexStr.contains("FB1") && (ActivateSystem == true))) {
ActivateSystem = false;
asHexStr = "";
} else {
System.out.println("Here2");
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Received");
}
}
public static class SerialWriter implements Runnable {
OutputStream out;
SerialPortConnector main = null;
public SerialWriter(SerialPortConnector twoWaySerialComm,
OutputStream out) {
main = twoWaySerialComm;
this.out = out;
}
public void send(String stringToSend) {
try {
int intToSend = Integer.parseInt(stringToSend);
this.out.write(intToSend);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
int c = 0;
Thread.sleep(1000);
if (asHexStr == "") {
System.out.println("Here");
// ActivateSystem = false;
}
}
// catch ( IOException e )
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main(String[] args) {
try {
(new SerialPortConnector()).connect("COM12");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have stated this in a comment:
I need to be able to detect that the id has stopped and after a
timeout(or after it not detecting the id a few times in a row) then
send a url call( i already have a class to send the call)-this should
only be sent once.while it is reading the id however another url call
should be sent again-once only
If I understand this right then you need to check for two different things:
The device stops at sending the ID.
The device sends a number of empty ID's.
This requirement is a kind of tricky. As I've said if no data arrives to the serial port then no serial port event will be fired. I think you can use a Timer to check the timeout and use a counter to register the number of empty ID's arrived. Something like this:
int numberOfEmptyIds = 0;
int maxNumberOfAttempts = 5;
boolean urlSent = false;
long timeoutInMillis = 10000; // let's say 10000 millis, equivalent to 10 seconds
Timer timer = null;
public void connect(String portName) throws Exception {
...
scheduleTimer();
}
public void serialEvent(SerialPortEvent evt) {
if(evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
while(in.read(buffer) > -1) {
String asHexStr = DatatypeConverter.printHexBinary(buffer);
if(asHexStr.contains("FB1")) {
scheduleTimer();
numberOfEmptyIds = 0;
} else {
numberOfEmtyIds++;
if(numberOfEmptyIds == maxNumberOfAttempts && !urlSent) {
// send the url here
}
}
}
} catch (IOException ex) {
// Log the exception here
}
}
}
private void scheduleTimer() {
if(timer != null) {
timer.cancel();
}
timer = new Timer("Timeout");
TimerTask task = new TimerTask() {
#Override
public void run() {
if(!urlSent) {
// send the url here
}
}
};
timer.schedule(task, timeoutInMillis);
}
I don't know if this is exactly what you need but hope it be helpful.
I am sending an analog signal to an android app via Ethernet. The goal is to control the alpha channel of some shapes being drawn. The code applies specifically to a rectangle. I've gotten both tutorials to work separately. The communications one recieves the signal and prints the value to screen. The graphics one draws a rectangle and moves it around on the screen based on touch events.
It gets an NullExceptionError on the socket = serverSocket.accept() line. This does not happen separately.
I've denoted which part is part of the graphics tutorial and which part is the communications tutorial. Some parts like onCreate are combined.
Thanks
public class MainActivity extends Activity implements OnTouchListener {
DrawView v;
float x;
float y;
Bitmap pic;
int alpha;
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
public static final int SERVERPORT = 6000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
v.setOnTouchListener(this);
setContentView(v);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
finish();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
//communications tutorial
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted() && socket==null) {
try {
socket = serverSocket.accept(); //null exception here
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();
int value = Integer.parseInt(read);
alpha=value*(255/1023);
//updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//end communications tutorial
//graphics tutorial
private void init(){
v = new DrawView(this);
//pic = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
x = 0;
y = 0;
alpha=255;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class DrawView extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean running = false;
public DrawView(Context c){
super(c);
holder = getHolder();
}
public void run() {
while(running){
if(holder.getSurface().isValid()){
Canvas c = holder.lockCanvas();
c.drawARGB(255, 0, 0, 0);
//c.drawBitmap(pic, x-pic.getWidth(), y-pic.getHeight(), null);
Paint myPaint = new Paint();
myPaint.setColor(Color.rgb(255, 255, 255));
myPaint.setAlpha(alpha);
// TODO implement alpha //myPaint.setAlpha(a);
c.drawRect(x-100,y-100,x+100,y+100,myPaint);
holder.unlockCanvasAndPost(c);
}
}
}
public void pause(){
running = false;
while(true){
try{
t.join();
}catch(InterruptedException e){
e.printStackTrace();
}break;
}
t = null;
}
public void resume(){
running = true;
t = new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent me) {
x = me.getX();
y = me.getY();
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event){
if((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE) {
if(event.getPointerCount() == 2) {
x = event.getX(0);
y = event.getY(0);
}
}
return true;
}
//end graphics tutorial
}
Look at:
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
When Server socket creation fails (i'e port is already used) you just pring the stack trace and continue to next lines as if the socket was created.
It gets an nullExceptionError on the socket = serverSocket.accept() line.
It doesn't, actually. It throws a NullPointerException, which means that serverSocket must be null.
This does not happen separately.
Whatever that means.
while (!Thread.currentThread().isInterrupted() && socket==null) {
The point of the socket == null test escapes me. All it accomplishes is ensuring that you only ever process one connection at a time. Is that really your intention? If so, why?
I'm creating 2 programs which one of them sends UDP packets from an Adnroid device and a second one (Java) receives them. So it works good if I use WiFi-router. But if I use a direct connection the Java application doesn't receive these packets. Under the direct connection I mean creating HOTSPOT on computer and connecting to it by the Android device. I used code snippet bellow:
Server's code:
public class UDPServer {
InetAddress groupAddress;
DatagramPacket packet;
byte[] buffer;
DatagramSocket socket;
static String ip = "227.0.25.57";
static int port = 6789;
private boolean isRun = false;
private String message = "";
private int broadcastInterval;
public void StopBroadcasting(){
isRun = false;
}
public void StartBroadcasting(String message, int broadcastInterval){
isRun = true;
this.message = message;
this.broadcastInterval = broadcastInterval;
new Thread(runner).start();
}
Runnable runner = new Runnable() {
#Override
public void run() {
while(isRun){
try {
SendBroadcastMessage(message);
System.out.println("msg sended...");
Thread.sleep(broadcastInterval);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Stopping UDPServer...");
}
};
public UDPServer() {
buffer = new byte[4096];
try {
groupAddress = InetAddress.getByName(ip);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket = new DatagramSocket();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SendBroadcastMessage(String msg) throws IOException{
if(msg==null) return;
buffer = msg.getBytes();
packet = new //DatagramPacket(buffer, buffer.length);
DatagramPacket(buffer, buffer.length, groupAddress, port);
socket.send(packet);
}
public static void Send(String msg){
try {
InetAddress group = InetAddress.getByName(ip);
MulticastSocket s = new MulticastSocket(port);
s.joinGroup(group);
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),
group, port);
s.send(hi);
System.out.println("send...");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Client's code:
public class UDPClient {}
MulticastSocket socket;
InetAddress groupAddress;
DatagramPacket packet;
byte[] buffer;
static String ip = "227.0.25.57";
static int port = 6789;
public interface OnReceiveDataListener{
public abstract void onReceiveData(String data);
}
private OnReceiveDataListener ReceiveDataListener = null;
public void setReceiveDataListener(OnReceiveDataListener ReceiveDataListener) {
this.ReceiveDataListener = ReceiveDataListener;
}
public OnReceiveDataListener getReceiveDataListener() {
return ReceiveDataListener;
}
private boolean isRun = false;
private Thread broadcastReceiver;
public void StopBroadcasting(){
isRun = false;
if(broadcastReceiver!=null)
broadcastReceiver.interrupt();
}
public void StartBroadcasting(){
isRun = true;
broadcastReceiver = new Thread(runner);
broadcastReceiver.start();
}
Runnable runner = new Runnable() {
#Override
public void run() {
while(isRun){
try {
String msg = ReceiveBroadcastMessage();
if(ReceiveDataListener!=null)
ReceiveDataListener.onReceiveData(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public UDPClient(){
buffer = new byte[4096];
try {
groupAddress = InetAddress.getByName(ip);
socket = new MulticastSocket(port);
socket.joinGroup(groupAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String ReceiveBroadcastMessage() throws IOException{
packet = new DatagramPacket(buffer, buffer.length);
System.out.println("before receive");
socket.receive(packet);
System.out.println(packet.getData());
return new String(packet.getData());
}
public void DeInit(){
try {
socket.leaveGroup(groupAddress);
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
MulticastSocket msocket;
public static void Receive(){
MulticastSocket msocket;
try {
msocket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(ip);
msocket.joinGroup(group);
byte[] inbuf = new byte[1024];
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
System.out.println("before receive");
msocket.receive(packet);
System.out.println("after receive");
int numBytesReceived = packet.getLength();
System.out.println(new String(packet.getData()));
msocket.leaveGroup(group);
msocket.close();
System.out.println(numBytesReceived);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
If you could see I have 2 methods of sending and receiving packets. The both don't work! What do I wrong?
Help me please.
I've found solution:
http://code.google.com/p/boxeeremote/wiki/AndroidUDP