delay in receiving data from Android to Arduino - android

I'm connecting my android device to arduino via USB and I receive data immediately from arduino by using bulkTransfer, but when I'm going to send acknowledge signal back to arduino using the same command, it receives that some seconds later.
My arduino model is DUE, and the arduino side code is:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(49, OUTPUT);
}
void loop() {
String a;
int sensorValue[64];
for (int i = 0; i <= 63; i++)
{
sensorValue[i] = analogRead(A0) / 4;
a = a + char(sensorValue[i]);
}
char b;
while (1) {
Serial.print(a);
Serial.flush();
delay(2);
b = Serial.read();
if (b == '1')
{
break;
}
}
digitalWrite(49, HIGH);
delay(2000);
digitalWrite(49, LOW);
}
My android side code is:
public void onClick(View v) {
synchronized (this) {
if (usbDeviceConnection != null) {
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
try {
int chunkCounter = 0;
String strTemp = null;
while (chunkCounter < 1) {
byte[] message = new byte[64];
final int result = usbDeviceConnection.bulkTransfer(endpointIN, message, 64, 10);
if (result == 64) {
for (int intTemp = 0; intTemp < 64; intTemp++) {
strTemp += String.valueOf((char) message[intTemp]);
}
byte[] ack = new byte[1];
ack[0] = 1; //1 means I've got this chunk
synchronized(this) {
int resultAck = 0;
while (resultAck <= 0) {
resultAck = usbDeviceConnection.bulkTransfer(endpointOUT, ack, 1, 10);
}
}
chunkCounter++;
if (chunkCounter == 1) {
final String strTempFinal = strTemp;
tempflag = true;
runOnUiThread(new Runnable() {
#Override
public void run() {
txtGetData.setText(strTempFinal);
}
});
}
}
}
} catch (final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
myThread.start();
}
Any help would be appreciated.
thanks in advance.

Related

RealTime Graph Entry

Please understand that I am using Google Translator because I do not understand English well.
I am currently working on an application that draws an EMG sensor value sent by Arduino via Bluetooth communication and a smartphone draws a graph based on that value.
Currently the application configuration has one activity and one fragment.
The Bluetooth function is in the activity and the graph is in the fragment.
I want to have the graph drawn only when the value comes in via Bluetooth communication. What should I do?
The code now depends on the fact that the fragment receives a value, even though the fragment is requesting a value.
Fragment
private void feedMultiple() {
if (thread != null)
thread.interrupt();
final Runnable runnable = new Runnable() {
#Override
public void run() {
addEntry();
}
};
thread = new Thread(new Runnable() {
#Override
public void run() {
while (loop) {
// Don't generate garbage runnables inside the loop
getActivity().runOnUiThread(runnable);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break;
}
}
}
});
thread.start();
}
Activity
void beginListenForData() {
final Handler handler = new Handler();
readBufferPosition = 0;
readBuffer = new byte[1024];
mWorkerThread = new Thread(new Runnable()
{
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
try {
int byteAvailable = mInputStream.available();
if(byteAvailable > 0) {
byte[] packetBytes = new byte[byteAvailable];
mInputStream.read(packetBytes);
for(int i=0; i<byteAvailable; i++) {
byte b = packetBytes[i];
if(b == mCharDelimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes,"UTF-8");
readBufferPosition = 0;
handler.post(new Runnable(){
#Override
public void run() {
//raw = data.split("#");
bundle.putString("yValue1", data);
}
});
}
else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "데이터 수신 중 오류가 발생 했습니다.", Toast.LENGTH_LONG).show();
finish();
}
}
}
});
mWorkerThread.start();
}

How to display a single value in android Threads

In android , i create a application based on RFID Card Reader on mobile. While i tapping Card on RFID Reader it generates same value at many times until the card untapped from the reader.
I want to show only one value per tapping card on RFID reader. Here i place my code and Sample snapshot of my application.
Guide me and tell solution for my problem.
public static MediaPlayer mp;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
Button readEnButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
long wait_sec=3000;
byte[] readData; //similar to data.
public static final int readLength = 1024; // changed length from 512
public int iavailable = 0;
char[] readDataToText;
//char readDataToTextSudha;
public boolean bReadThreadGoing = false;
public readThread read_thread;
public static D2xxManager ftD2xx = null;
boolean uart_configured = false;
// Empty Constructor
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readData = new byte[readLength];
readDataToText = new char[readLength];
//readDataToTextSudha = new char;
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
readEnButton = (Button) findViewById(R.id.readEnButton);
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
//Opening Coding
if (DevCount <= 0) {
createDeviceList();
} else {
connectFunction();
}
//Configuration coding
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else {
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
readEnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else if (uart_configured == false) {
Toast.makeText(getApplicationContext(), "UART not configure yet...", Toast.LENGTH_SHORT).show();
return;
} else {
EnableRead();
}
}
});
}
public void EnableRead() {
iEnableReadFlag = (iEnableReadFlag + 1) % 2;
if (iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
Toast.makeText(getApplicationContext(),"Read Enabled",Toast.LENGTH_LONG).show();
} else {
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
Toast.makeText(getApplicationContext(),"Read Disabled",Toast.LENGTH_LONG).show();
}
}
public void createDeviceList() {
int tempDevCount = ftD2xx.createDeviceInfoList(getApplicationContext());
if (tempDevCount > 0) {
if (DevCount != tempDevCount) {
DevCount = tempDevCount;
updatePortNumberSelector();
}
} else {
DevCount = -1;
currentIndex = -1;
}
};
public void disconnectFunction() {
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ftDev != null) {
synchronized (ftDev) {
if (true == ftDev.isOpen()) {
ftDev.close();
}
}
}
}
public void connectFunction() {
int tmpProtNumber = openIndex + 1;
if (currentIndex != openIndex) {
if (null == ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
}
}
uart_configured = false;
} else {
Toast.makeText(getApplicationContext(), "Device port " + tmpProtNumber + " is already opened", Toast.LENGTH_LONG).show();
return;
}
if (ftDev == null) {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen()) {
currentIndex = openIndex;
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if (false == bReadThreadGoing) {
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
} else {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
}
}
public void updatePortNumberSelector() {
if (DevCount == 2) {
Toast.makeText(getApplicationContext(), "2 port device attached", Toast.LENGTH_SHORT).show();
} else if (DevCount == 4) {
Toast.makeText(getApplicationContext(), "4 port device attached", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "1 port device attached", Toast.LENGTH_SHORT).show();
}
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
uart_configured = true;
Toast.makeText(getApplicationContext(), "Config done", Toast.LENGTH_SHORT).show();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (iavailable > 0) {
mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread {
Handler mHandler;
readThread(Handler h) {
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run() {
int i;
while (true == bReadThreadGoing) {
try {
Thread.sleep(1000); //changed
} catch (InterruptedException e) {
}
synchronized (ftDev) {
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if (iavailable > readLength) {
iavailable = readLength;
}
ftDev.read(readData, iavailable,wait_sec);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if (DevCount > 0) {
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
My problem would snapped here
Getting Value continuously from Reader
I want this type of value when i tap the card
If i tap some other cards, old card value replaces from the new one.
Guide me.
Thanks in Advance
I got the answer by using of Threads. When the card tapping it get some values after sleep of one or two seconds only the next value have to get from the reader.
public void run() {
int i;
while (true == bReadThreadGoing) { // Means Make sure , getting value from Reader
try {
Thread.sleep(1000); // Wait for a second to get another value.
clearText(); //clear the old value and get new value.
} catch (InterruptedException e) {
}
And clearing the edittext by using this command.
public void clearText() {
runOnUiThread(new Runnable() {
public void run() {
readText.setText("");
}
});
}

The response time to a Bluetooth connection between Arduino and Android is proportional to the distance?

I'm trying to get the distance between an Android device and a Arduino. To do this, I thought I'd use the formula of calculating networks latency, as seen in this link:
How to calculate packet time from latency and bandwidth
where the propagation time would be given to obtaining the time I spent to send a signal to the Arduino and get the answer divided by 2 (one-way time care). However, the time I have got varies even when not moving the Android device, and even increasing the distance, remains in the same range, between 1 and 11 milliseconds. My idea is wrong or the way I am doing it? I can even make these deductions have I done? Here is my code:
My button click
public void onLedOnClick(View v)
{
long avg = 0;
for(int i = 1; i < 31; i++){
long t1 = System.currentTimeMillis();
sendData("1");
beginListenForData();
long t2 = System.currentTimeMillis();
avg = (avg + (t2-t1)) / i;
txtAnswerTime.setText("Answer time:" + String.valueOf((t2-t1)) + "ms");
}
sendData("3");
}
my sendData method:
public void sendData(String data){
if (btSocket != null) {
try {
// allows the output data from a socket
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
String mensagem = data;
byte[] msgBuffer = mensagem.getBytes();
try {
// sends content by bluetooth
outStream.write(msgBuffer);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(),
"Bluetooth is not connected", Toast.LENGTH_SHORT).show();
}
}
My getData method:
public void beginListenForData()
{
if (btSocket != null) {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
try {
mmInputStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
txtBytesSize.setText("Received data: "+data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
} else {
Toast.makeText(getApplicationContext(),
"Bluetooth is not connected", Toast.LENGTH_SHORT).show();
}
}
My Arduino code:
const int ledPin = 7;
byte serialA;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
if (Serial.available() > 0) {serialA = Serial.read();Serial.println(serialA);}
switch (serialA) {
case 49://49 is the bytes of "1"
digitalWrite(ledPin, HIGH);
Serial.println(serialA);
break;
case 50: //50 is the bytes of "2"
digitalWrite(ledPin, LOW);
Serial.println(serialA);
break;
break;
}
}

Android Arduino Bluetooth communication

I can send data from a phone phone to an Arduino, but I can't see the data sent in from the Arduino in the phone. I think that the program never enters in the handler part but I don't know how to solve it.
This is the Android code:
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++) {
byte b = packetBytes[i];
if(b == delimiter) {
///Here is the problem
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
texto.setText("data");
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
And this is the Arduino code:
char val; // variable to receive data from the serial port
int ledpin = 13; // LED connected to pin 48 (on-board LED)
void setup() {
pinMode(ledpin, OUTPUT);
// pin 48 (on-board LED) as OUTPUT
Serial.begin(9600);
// start serial communication at 9600bps
}
void loop() {
if(Serial.available()) {
// if data is available to read
val = Serial.read();
// read it and store it in 'val'
}
if(val == 'H') {
// if 'H' was received
digitalWrite(ledpin, HIGH);
// turn ON the LED
delay(1000);
Serial.print("Recibido");
} else {
//digitalWrite(ledpin, LOW);
// otherwise turn it OFF
}
delay(100);
// wait 100ms for next reading
}

Why can't the server recognize what the client is sending?

I am writing a an Android app which is essentially an network based tic tac toe, There is a server on the computer an two Android phones as clients playing against each other. To accomplish this task I created a multithreaded server that can deal with both clients, and I created the two clients and I made them receive what the server sends them in a separate thread and using a handler I change the UI once the server sends the other player's move.
The problem is that the serverThread never recognizes what any of the clients send. The protocol I am using between the client and the server is a number based protocol, once the client clicks on a tile, a number is sent to the server, the server adds this number to an array, and sends it to all the threads(Both clients) so that they can change this tile from tile to "X" or "O" depending on the number
Here is the code for the listener of two buttons, all other buttons are similar
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (value == 1) {
numberSent = 0;
Global.os.println(Integer.toString(0));
Global.os.flush();
Log.i("Sent", "The Zero");
}
else if (value == 2) {
numberSent = 9;
Global.os.println(Integer.toString(Activity2.numberSent));
Global.os.flush();
}
}
});
b2.setImageResource(R.drawable.tile);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(value == 1) {
numberSent = 1;
Global.os.println(Integer.toString(Activity2.numberSent));
Global.os.flush();
}
else if(value == 2) {
numberSent = 10;
Global.os.println(Integer.toString(Activity2.numberSent));
Global.os.flush();
}
}
});
Here is the code for the ClientThread (The one that handles messages recieved from the server and has the handler that changes the UI)
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class ClientThread implements Runnable {
int s;
public void run() {
try {
try {
Global.s = new Socket("10.0.2.2", 5555);
Global.is = new DataInputStream(Global.s.getInputStream());
Global.os = new PrintStream(Global.s.getOutputStream());
Global.os.println(Integer.toString(100));
Log.i("Socket", "Created");
} catch (Exception e) {
e.printStackTrace();
}
while (true) {
Log.i("In the", "While");
try {
String S = null;
while ((S = Global.is.readLine()) != null) {
Log.d("ServerActivity", "line");
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Global.os.print(Integer.toString(Activity2.numberSent));
try {
String S = Global.is.readLine();
s = Integer.parseInt(S);
if (s == 0) {
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b1.setImageResource(R.drawable.x);
}
});
}
else if(s == 1){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b2.setImageResource(R.drawable.x);
}
});
}
else if(s == 2){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b3.setImageResource(R.drawable.x);
}
});
}
else if(s == 3){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b4.setImageResource(R.drawable.x);
}
});
}
else if(s == 4){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b5.setImageResource(R.drawable.x);
}
});
}
else if(s == 5){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b6.setImageResource(R.drawable.x);
}
});
}
else if(s == 6){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b7.setImageResource(R.drawable.x);
}
});
}
else if(s == 7){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b8.setImageResource(R.drawable.x);
}
});
}
else if(s == 8){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b9.setImageResource(R.drawable.x);
}
});
}
else if(s == 9){
Activity2.handler.post(new Runnable() {
public void run() {
Activity2.b1.setImageResource(R.drawable.o);
}
});
}
else if(s == 10){
Activity2.handler.post(new Runnable() {
public void run() {
Activity2.b2.setImageResource(R.drawable.o);
}
});
}
else if(s == 11){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b3.setImageResource(R.drawable.o);
}
});
}
else if(s == 12){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b4.setImageResource(R.drawable.o);
}
});
}
else if(s == 13){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b5.setImageResource(R.drawable.o);
}
});
}
else if(s == 14){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b6.setImageResource(R.drawable.o);
}
});
}
else if(s == 15){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b7.setImageResource(R.drawable.o);
}
});
}
else if(s == 16){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b8.setImageResource(R.drawable.o);
}
});
}
else if(s == 17){
Activity2.handler.post(new Runnable() {
#Override
public void run() {
Activity2.b9.setImageResource(R.drawable.o);
}
});
}
else {
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
}
}
}
Here is the code of my server thread
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
class ServerThread extends Thread {
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
ServerThread t[];
public String received;
public ServerThread(Socket clientSocket, ServerThread[] t){
this.clientSocket=clientSocket;
this.t=t;
}
public void run() {
try {
is = new DataInputStream(clientSocket.getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
try {
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
try{
// Once the socket is open all the work will be here!!!!!!
while(true) {
System.out.print("In the while");
received = is.readLine();
int s = Integer.parseInt(received);
if(s == 100) {
System.out.print("I recieved the 100");
}
if(s == 0) {
System.out.println("I recieved the 0");
XOServer.boardArray[0] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 0;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 1) {
XOServer.boardArray[1] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 1;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 2) {
XOServer.boardArray[2] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 2;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 3) {
XOServer.boardArray[3] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 3;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 4) {
XOServer.boardArray[4] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 4;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 5) {
XOServer.boardArray[5] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 5;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 6) {
XOServer.boardArray[6] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 6;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 7) {
XOServer.boardArray[7] = 1;
XOServer.turn = true;
System.out.print("I recieved the 7");
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 7;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 8) {
XOServer.boardArray[8] = 1;
XOServer.turn = true;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 8;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 9) {
XOServer.boardArray[0] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 9;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 10) {
XOServer.boardArray[1] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 10;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 11) {
XOServer.boardArray[2] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 11;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 12) {
XOServer.boardArray[3] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 12;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 13) {
XOServer.boardArray[4] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 13;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 14)
XOServer.boardArray[5] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 14;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 15) {
XOServer.boardArray[6] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 15;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 16) {
XOServer.boardArray[7] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 16;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else if(s == 17) {
XOServer.boardArray[8] = 2;
XOServer.turn = false;
for(int i = 0; i<=t.length; i++) {
if (t[i]!=null) {
XOServer.sentValue = 17;
t[i].os.println(Integer.toString(XOServer.sentValue));
t[i].os.flush();
}
}
}
else {
}
}
}
catch (Exception e){
System.out.print(e);
}
}
Here is the code for my server
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class XOServer{
// Declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
static PrintStream os = null;
static DataInputStream is = null;
static int sentValue;
// This chat server can accept up to 10 clients' connections
static ServerThread t[] = new ServerThread[10];
public static int [] boardArray = new int[9];
public static boolean turn = false;
public static void main(String args[]) {
// The default port
int port_number=5555;
if (args.length < 1) {
System.out.println("Usage: java MultiThreadChatServer \n"+
"Now using port number="+port_number);
} else {
port_number=Integer.valueOf(args[0]).intValue();
}
for(int i = 0; i <=8; i++ ) {
boardArray[i] = 0;
}
// Initialization section:
// Try to open a server socket on port port_number (default 2222)
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
serverSocket = new ServerSocket(port_number);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams for this socket will be created in
// client's thread since every client is served by the server in
// an individual thread
while (true) {
try {
clientSocket = serverSocket.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
for(int i=0; i<=9; i++){
if(t[i]==null) {
(t[i] = new ServerThread(clientSocket,t)).start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
I think your problem (or at least one problem) is on the server. When the client connects you are setting:
os = new PrintStream(clientSocket.getOutputStream());
os is a static variable inside of the server. This is wrong.
static PrintStream os
Each client thread must have it's own separate PrintStream. You will need to get the input/output streams and pass them into your handler.
clientSocket = serverSocket.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
... new ServerThread(is, os, clientSocket, t)).start();
Also, I don't understand why you fork 10 threads for each client connection. That seems wrong. Typically you could accept a client connection and then fork 1 thread to handle that specific connection with that input and output streams.

Categories

Resources