android socket connection to update graphics - java

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?

Related

Application doesn't enter thread

i'm trying to create a chat application using multhitreading functionalities and here's the code of the session class that handles connections and of the server class that accept connections:
Session class:
public class Session extends Thread{
Socket Sock;
BufferedReader din;
PrintWriter dout;
Thread receive;
Server serv;
boolean connected = false;
String lineSep = System.getProperty("line.separator");
public Session(Socket s, Server n){
super("ThreadSessions");
this.Sock = s;
this.serv = n;
}
public void run(){
try{
din = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
dout = new PrintWriter(Sock.getOutputStream());
connected = true;
Receive();
}
catch(IOException ioe){
ioe.printStackTrace();
}
receive.start();
}
public void sendTo(String text){
dout.write(text);
dout.flush();
}
public void sendToAll(String text){
for(int ind = 0; ind < serv.sessions.size(); ind++){
Session s = serv.sessions.get(ind);
s.sendToAll(text);
}
}
public void Receive(){
receive = new Thread(new Runnable(){
#Override
public void run() {
receive = new Thread(new Runnable(){
String msgIn;
public void run() {
while(connected){
try{
msgIn = din.readLine();
if(msgIn != "" || msgIn != null){
System.out.println(msgIn);
msgIn = "";
}else{
}
}
catch(SocketException exc){
exc.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
});
}
}
Server class:
public class Server {
private JFrame frame;
private JTextField txtPort;
JTextArea textArea, textSessions;
String lineSep = System.getProperty("line.separator");
ServerSocket ServSock;
Socket Sock;
String port;
public JTextField textField;
int numbSess = 0, actSess = 0;
ArrayList<Session> sessions = new ArrayList<Session>();
boolean shouldRun = true;
public static void main(String[] args)
{
Server window = new Server();
window.frame.setVisible(true);
}
public Server() {
initializeComponents(); //This void initializes the graphic components
}
private void Connect(){
port = txtPort.getText();
int portN = 0;
try{
portN = Integer.parseInt(port);
}
catch(NumberFormatException exc)
{
exc.printStackTrace();
}
try{
ServSock = new ServerSocket(9081);
while(shouldRun){
Sock = ServSock.accept();
String ip = Sock.getInetAddress().getHostAddress();
Session s = new Session(Sock, this);
s.start();
sessions.add(s);
numbSess++;
}
}
catch(Exception exc){
exc.printStackTrace();
System.exit(3);
}
}
private void initializeComponents() {
[...]
Button btnConn = new JButton("Open Connection");
btnConn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connect();
}
});
btnConn.setBackground(new Color(0, 0, 0));
btnConn.setForeground(new Color(0, 128, 0));
btnConn.setBounds(160, 13, 137, 25);
frame.getContentPane().add(btnConn);
[...]
}
What i want to do is creating a chat application that can handle more connection at the same time but instead of entering the first connection(session in my app.) it continues waiting for other connections and adding those in the arrayList.
Probably the code is full of mistakes so forgive me.
If somebody knows a better way to create a server that can handle more client's connections those are welcome.
Hope someone can help me, thanks in advance.
instead of entering the first connection(session in my app.) it continues waiting for other connections and adding those in the arrayList
This is due to how your threads are set up
Each time you make and start a session, its run method is called...
public void run()
{
Receive();
[...]
receive.start();
}
...which in turn sets up receive in Receive();
public void Receive()
{
receive = new Thread(new Runnable()
{
public void run()
{
receive = new Thread(new Runnable()
{
public void run()
{
//your actual code that you wanted to run
}
});
}
});
}
The thread created when ran, will do one thing, set up receive yet again, with the code you wanted the first time
receive = new Thread(new Runnable()
{
public void run()
{
//your actual code that you wanted to run
}
});
But after you call Receive();, you only called receive.start(); once
You'll either need to call it twice, and somehow ensure that it updated in time, or just remove the excess thread

JFrame freezes when button is pressed and operations from the other Class are ran [duplicate]

I'm writing a program that constantly pings a server. I wrote the code to check it once and put the ping in a JLabel and put it in a method called setPing().
Here is my code
private void formWindowOpened(java.awt.event.WindowEvent evt) {
setPing();
}
That worked but only did it once, so I did:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
for(;;){
setPing();
}
}
But this doesn't even work for the first time.
I didnt put the setPing method because it was too long so here it is:
public String setPing(){
Runtime runtime = Runtime.getRuntime();
try{
Process process = runtime.exec("ping lol.garena.com");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
int i = 0;
i = line.indexOf("Average");
if(i > 0){
String finalPing = "";
line.toCharArray();
try
{
finalPing = "";
for(int x = i; x < i + 17; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException e)
{
try
{
finalPing = "";
for(int x = i; x < i + 16; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException f)
{
try
{
finalPing = "";
for(int x = i; x < i + 15; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException g){}
}
}
String final1Ping = finalPing.replaceAll("[^0-9]", "");
return final1Ping;
}
}
}catch(IOException e){
}
return "";
}
UPDATE
Just in case this is important, Im using netbeans. I created a form and put this code in the formWindowOpened evt instead of calling it in main:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(1000, timerListener);
timer.start();
jLabel1.setText(label.getText());
timer.stop();
// TODO add your handling code here:
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime("lol.garena.com");
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public JComponent getUI() {
return label;
}
public static int pingTime(String hostnameOrIP) {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
Use a Swing Timer for repeating tasks & a SwingWorker for long running tasks. E.G. of both below - it uses a Timer to repeatedly perform a 'long running' task (a ping) in a SwingWorker.
See Concurrency in Swing for more details on the Event Dispatch Thread and doing long running or repeating tasks in a GUI.
This code combines a long running task ('pinging' a server) using SwingWorker invoked from a repeating task (updating the JLabel repeatedly with the times) using a Swing based Timer.
import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;
public class LabelUpdateUsingTimer {
static String hostnameOrIP = "stackoverflow.com";
int delay = 5000;
JLabel label = new JLabel("0000");
LabelUpdateUsingTimer() {
label.setFont(label.getFont().deriveFont(120f));
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(delay, timerListener);
timer.start();
JOptionPane.showMessageDialog(
null, label, hostnameOrIP, JOptionPane.INFORMATION_MESSAGE);
timer.stop();
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime();
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public static int pingTime() {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (Exception weTried) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception weTried) {}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new LabelUpdateUsingTimer();
}
};
SwingUtilities.invokeLater(r);
}
}
You could use a Thread. The problem is you are blocking the main thread, thereby blocking your program. To get around this, start a background Thread to update components repeatedly.
(Note: you need to update GUI components on the EDT, so use SwingUtilities.invokeLater)
(new Thread((new Runnable(){
#Override
public void run(){
while(true){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
refToJLabel.setText(Math.random());
}
});
}
}
}))).start();

Following method call prevents JLabel from getting visible [duplicate]

I'm writing a program that constantly pings a server. I wrote the code to check it once and put the ping in a JLabel and put it in a method called setPing().
Here is my code
private void formWindowOpened(java.awt.event.WindowEvent evt) {
setPing();
}
That worked but only did it once, so I did:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
for(;;){
setPing();
}
}
But this doesn't even work for the first time.
I didnt put the setPing method because it was too long so here it is:
public String setPing(){
Runtime runtime = Runtime.getRuntime();
try{
Process process = runtime.exec("ping lol.garena.com");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
int i = 0;
i = line.indexOf("Average");
if(i > 0){
String finalPing = "";
line.toCharArray();
try
{
finalPing = "";
for(int x = i; x < i + 17; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException e)
{
try
{
finalPing = "";
for(int x = i; x < i + 16; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException f)
{
try
{
finalPing = "";
for(int x = i; x < i + 15; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException g){}
}
}
String final1Ping = finalPing.replaceAll("[^0-9]", "");
return final1Ping;
}
}
}catch(IOException e){
}
return "";
}
UPDATE
Just in case this is important, Im using netbeans. I created a form and put this code in the formWindowOpened evt instead of calling it in main:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(1000, timerListener);
timer.start();
jLabel1.setText(label.getText());
timer.stop();
// TODO add your handling code here:
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime("lol.garena.com");
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public JComponent getUI() {
return label;
}
public static int pingTime(String hostnameOrIP) {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
Use a Swing Timer for repeating tasks & a SwingWorker for long running tasks. E.G. of both below - it uses a Timer to repeatedly perform a 'long running' task (a ping) in a SwingWorker.
See Concurrency in Swing for more details on the Event Dispatch Thread and doing long running or repeating tasks in a GUI.
This code combines a long running task ('pinging' a server) using SwingWorker invoked from a repeating task (updating the JLabel repeatedly with the times) using a Swing based Timer.
import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;
public class LabelUpdateUsingTimer {
static String hostnameOrIP = "stackoverflow.com";
int delay = 5000;
JLabel label = new JLabel("0000");
LabelUpdateUsingTimer() {
label.setFont(label.getFont().deriveFont(120f));
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(delay, timerListener);
timer.start();
JOptionPane.showMessageDialog(
null, label, hostnameOrIP, JOptionPane.INFORMATION_MESSAGE);
timer.stop();
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime();
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public static int pingTime() {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (Exception weTried) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception weTried) {}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new LabelUpdateUsingTimer();
}
};
SwingUtilities.invokeLater(r);
}
}
You could use a Thread. The problem is you are blocking the main thread, thereby blocking your program. To get around this, start a background Thread to update components repeatedly.
(Note: you need to update GUI components on the EDT, so use SwingUtilities.invokeLater)
(new Thread((new Runnable(){
#Override
public void run(){
while(true){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
refToJLabel.setText(Math.random());
}
});
}
}
}))).start();

Serial Data Event Listener Java

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.

Optimizing Java Socket Sending Android to PC

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.

Categories