send msg from senders to receivers (in concurrency mode) in java - multithreading

I want to write program that use one server that receive msg from reporters in specific port and send online msg to client (readers) that are connected on another specific port ...
tip1 =>
my server has two open port ... one specific for senders and another for reader...
tip2 =>
when msg is received from sender in server => we(server) should send this msg to all online client that listen
how can I implement them...
I have problem in send msg from server to "all" client!

You can do it like this -
public class SenderReceiver {
private static volatile boolean serverStarted;
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 25000;
private static final List<ReceiverConnectionHandler> handlers = new CopyOnWriteArrayList<ReceiverConnectionHandler>();
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) {
// start server
executorService.submit(new SenderReceiver().new Server());
// wait until started
while (!serverStarted) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// start receiver threads
int i = 0;
while (i++ < 10) {
executorService.submit(new Receiver(SERVER_HOST, SERVER_PORT));
}
// start sender threads
i = 0;
while (i++ < 5) {
executorService.submit(new Sender(SERVER_HOST, SERVER_PORT));
}
}
private class Server implements Runnable {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
serverStarted = true;
System.out.println("Server started");
while (true) {
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String connectionName = br.readLine();
if ("sender".equals(connectionName)) {
executorService.submit(new SenderConnectionHandler(br, handlers));
} else {
ReceiverConnectionHandler handler = new ReceiverConnectionHandler(socket);
handlers.add(handler);
executorService.submit(handler);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class SenderConnectionHandler implements Runnable {
private BufferedReader br;
private List<ReceiverConnectionHandler> handlers;
public SenderConnectionHandler(BufferedReader br, List<ReceiverConnectionHandler> handlers) {
this.br = br;
this.handlers = handlers;
}
public void run() {
try {
String message;
while ((message = br.readLine()) != null) {
Thread.sleep(1000); // just allowing all clients to be registered
for (ReceiverConnectionHandler handler : handlers) {
handler.update(message);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
private class ReceiverConnectionHandler implements Runnable {
private Socket receiverSocket;
private final BlockingQueue<String> messages = new LinkedBlockingQueue<>();
public ReceiverConnectionHandler(Socket socket) {
this.receiverSocket = socket;
}
public void run() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(receiverSocket.getOutputStream()));
String message;
while ((message = messages.poll(1, TimeUnit.SECONDS)) != null) {
bw.write(message);
bw.newLine();
bw.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void update(Object message) {
if (message instanceof String) {
messages.add((String) message);
}
}
}
}
class Sender implements Runnable {
private static AtomicInteger senderCount = new AtomicInteger(0);
private String serverHost;
private int serverPort;
public Sender(String serverHost, int serverPort) {
this.serverHost = serverHost;
this.serverPort = serverPort;
}
public void run() {
BufferedWriter bw = null;
try {
Socket socket = new Socket(serverHost, serverPort);
int senderNumber = senderCount.incrementAndGet();
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("sender");
bw.newLine();
String message = "This is a test message from sender " + senderNumber;
bw.write(message);
bw.newLine();
System.out.println("Sender " + senderNumber + " : " + message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class Receiver implements Runnable {
private static AtomicInteger receiverCount = new AtomicInteger(0);
private String serverHost;
private int serverPort;
public Receiver(String serverHost, int serverPort) {
this.serverHost = serverHost;
this.serverPort = serverPort;
}
public void run() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
Socket socket = new Socket(serverHost, serverPort);
int receiverNumber = receiverCount.incrementAndGet();
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("client");
bw.newLine();
bw.flush();
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while ((message = br.readLine()) != null) {
System.out.println("Receiver " + receiverNumber + ": " + message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

Related

Synchronously Send and Receive Bluetooth Data using Kotlin Coroutines

This has been the method so far to send and receive on bluetooth using Java with threading. But how do we do this using Kotlin's latest Coroutines? Alot of this old Java cold no longer translates to Kotlin 1.4+ either in terms of how to do threading. I read Kotlin is now using Coroutines instead of threads like before.
public class MainActivity extends AppCompatActivity {
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66")
public void pairDevice(View v) {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
Object[] devices = pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0]
ConnectThread connect = new ConnectThread(device,MY_UUID_INSECURE);
connect.start();
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) {
}
mmSocket = tmp;
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e1) {
}
}
//will talk about this in the 3rd video
connected(mmSocket);
}
}
private void connected(BluetoothSocket mmSocket) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
final String incomingMessage = new String(buffer, 0, bytes);
runOnUiThread(new Runnable() {
#Override
public void run() {
view_data.setText(incomingMessage);
}
});
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
}
public void SendMessage(View v) {
byte[] bytes = send_data.getText().toString().getBytes(Charset.defaultCharset());
mConnectedThread.write(bytes);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_data =(EditText) findViewById(R.id.editText);
view_data = (TextView) findViewById(R.id.textView);
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void Start_Server(View view) {
AcceptThread accept = new AcceptThread();
accept.start();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null ;
try{
tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("appname", MY_UUID_INSECURE);
}catch (IOException e){
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
}catch (IOException e){
}
//talk about this is in the 3rd
if(socket != null){
connected(socket);
}
}
}

retrofit2.0.0+okhttp3 download logging output OOM

addInterceptor ->HttpLoggingInterceptor bug-->OOM
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
File httpCacheDirectory = new File(MyApplication.mContext.getCacheDir(), "responses");
//设置缓存 10M
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
OkHttpClient client = null;
final TrustManager[] trustManager = new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
};
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client = new OkHttpClient.Builder().addInterceptor(interceptor).sslSocketFactory(sslSocketFactory).addInterceptor(new BaseInterceptor()).hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).cache(cache).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
_instance = new Retrofit.Builder().baseUrl(ConstantUtils.HOST)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();
}
return _instance.create(ICommonService.class);
RetrofitUtils.generateCommonService().down().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
LogUtils.e("errorrrrrrrrrr");
}
#Override
public void onNext(ResponseBody responseBody) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
byte[] by = responseBody.bytes();
File file = new File(BaseApplication.getContext().getFilesDir(), "download.apk");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(by);
LogUtils.e("length=======>",file.length()+"");
mainView.updateApk(file);
}catch (IOException e){
e.printStackTrace();
}finally {
if (bos != null)
{
try
{
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (fos != null)
{
try
{
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
LogUtils.e("success=========");
}
});
When you use HttpLoggingInterceptor.Level.BODY , then you try to download large file , will save all body in memory for log.
That's easy let to OOM .
Try to remove log body or just logging NONE , basic or header and try again.
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
Try this .
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
//设置缓存路径

SocketTimeoutException when testing on Android Studio simulator

When I attempt to connect through a socket to my Android App, I get the following error:
10-02 01: 32: 30.295 1738-1892 / me.schat E / schat / SimpleSocket: java.net.SocketTimeoutException: failed to connect to schat.me/188.40.116.82 (port 7667) after 20000ms
This error occurs only in the emulator. When i test directly on the phone it works.
Internet works on the emulator, the browser opens any website.
My socket code in its entirety
package me.schat.net;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import javax.net.SocketFactory;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class SimpleSocket {
private static final String TAG = "schat/SimpleSocket";
private final Object m_sendLock = new Object();
private boolean m_authorized = false; // true после успешной авторизации.
private DataInputStream m_in; // Поток чтения транспортных пакетов.
private DataOutputStream m_out; // Поток записи транспортных пакетов.
private Handler m_handler; // Объект доступа к потоку отправки пакетов.
private int m_reconnects = 0; // Число попыток восстановить соединение.
private long m_rxSequence = 0; // Счётчик полученных пакетов.
private long m_txSequence = 0; // Счётчик отправленных пакетов.
private Network network; // Информация для подключения.
private PacketListener m_packets; // Слушатель пакетов.
private Socket m_socket; // Сокет подключения.
private SocketListener m_listener; // Слушатель сокета.
private Thread m_thread; // Поток чтения пакетов.
private Timer m_timer; // Таймер обслуживающий соединение.
private TimerTask m_killTask; // Задача для отключения от сервера, если он не ответил за определённое время.
private TransportReader m_reader; // Объект чтения транспортных пакетов.
private ByteArrayOutputStream m_send = new ByteArrayOutputStream(); // Поток отправки пакетов.
public SimpleSocket(SocketListener listener, PacketListener packets) {
m_listener = listener;
m_packets = packets;
m_reader = new TransportReader(this);
m_timer = new Timer("SocketTimer");
HandlerThread thread = new HandlerThread("simplesocket-thread");
thread.start();
m_handler = new Handler(thread.getLooper());
}
public boolean connect(Network network) {
this.network = network;
return connect();
}
public boolean connect() {
Log.d(TAG, "connect()");
if ((m_thread != null && m_thread.isAlive()) || network == null)
return false;
m_thread = new Thread(new Runnable() {
public void run() {
Log.d(TAG, "RUN " + Thread.currentThread().getId());
int port = network.uri.getPort();
if (port == -1)
port = Protocol.DEFAULT_PORT;
try {
SocketAddress sockaddr = new InetSocketAddress(network.uri.getHost(), port);
SocketFactory factory = SocketFactory.getDefault();
m_socket = factory.createSocket();
m_socket.setTcpNoDelay(true);
m_socket.setKeepAlive(true);
m_socket.connect(sockaddr, Protocol.CONNECT_TIMEOUT);
m_in = new DataInputStream(new BufferedInputStream(m_socket.getInputStream()));
m_out = new DataOutputStream(new BufferedOutputStream(m_socket.getOutputStream()));
} catch (IOException ioe) {
Log.e(TAG, ioe.toString());
reconnect();
return;
}
catch (NullPointerException npe) {
Log.e(TAG, npe.toString());
reconnect();
return;
}
ping();
m_reconnects = 0;
m_listener.onConnect();
m_listener.onAuthRequired();
try {
m_reader.start(m_in);
} catch (IOException ioe) {
Log.e(TAG, "Socket read exception", ioe);
reconnect();
}
}
});
m_thread.start();
return true;
}
public boolean send(final WritablePacket packet) {
List<WritablePacket> packets = new ArrayList<WritablePacket>();
packets.add(packet);
return send(packets);
}
public boolean send(final List<WritablePacket> packets) {
if (packets.isEmpty())
return false;
m_handler.post(new Runnable() {
public void run() {
synchronized (m_sendLock) {
try {
List<byte[]> raws = new ArrayList<byte[]>(packets.size());
int options = Protocol.NO_OPTIONS;
for (WritablePacket packet : packets) {
final byte[] raw = packet.write(m_send).toByteArray();
raws.add(raw);
if (raw.length > 65535)
options = Protocol.HUGE_PACKETS;
}
new TransportWriter(m_out, raws, m_txSequence, options);
m_txSequence++;
} catch (IOException ioe) {
Log.e(TAG, "Send failed", ioe);
}
}
}
});
return true;
}
public final Network getNetwork() {
return network;
}
public final PacketListener packets() {
return m_packets;
}
public final synchronized boolean isAuthorized() {
return m_authorized;
}
public final synchronized void setAuthorized(boolean authorized) {
m_authorized = authorized;
}
public final void leave() {
m_reconnects = -1;
disconnect();
}
/**
* Отключение от сервера.
*/
public final void disconnect() {
if (m_socket == null)
return;
m_handler.post(new Runnable() {
public void run() {
try {
if (m_socket != null) {
m_socket.close();
m_socket = null;
}
} catch (IOException ioe) {
Log.e(TAG, "Error while disconnecting", ioe);
}
if (m_thread != null) {
m_thread.interrupt();
m_thread = null;
}
}
});
}
public final void ping() {
if (m_killTask != null)
m_killTask.cancel();
m_timer.schedule(new TimerTask() {
public void run() {
if (isAuthorized()) {
transmit(new byte[0], Protocol.INTERNAL_PACKET);
m_killTask = new TimerTask() {
public void run() {
disconnect();
}
};
m_timer.schedule(m_killTask, Protocol.REPLY_TIMEOUT);
} else
disconnect();
}
}, Protocol.IDLE_TIMEOUT);
}
private void reconnect() {
if (m_thread != null) {
m_thread.interrupt();
m_thread = null;
}
if (m_reconnects == -1)
return;
if (m_reconnects >= Protocol.MAX_FAST_RECONNECTS + Protocol.MAX_NORMAL_RECONNECTS)
m_reconnects = 0;
++m_reconnects;
m_timer.schedule(new TimerTask() {
public void run() {
connect();
}
}, m_reconnects <= Protocol.MAX_FAST_RECONNECTS ? Protocol.FAST_RECONNECT_TIME : Protocol.NORMAL_RECONNECT_TIME);
m_listener.onReconnect();
}
private boolean transmit(final byte[] packet, final int options) {
List<byte[]> packets = new ArrayList<byte[]>();
packets.add(packet);
return transmit(packets, options);
}
private boolean transmit(final List<byte[]> packets, final int options) {
// Log.d(TAG, "transmit(List<byte[]> packets)");
if (packets.isEmpty())
return false;
m_handler.post(new Runnable() {
public void run() {
synchronized (m_sendLock) {
try {
new TransportWriter(m_out, packets, m_txSequence, options);
if (options != Protocol.INTERNAL_PACKET)
m_txSequence++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
return false;
}
}

javax.bluetooth.BluetoothExeption: unable to swithc master

i want to write bluetooth base app for send and recive string between two device . i have problem . i send string from device A and device B recive it but when i try to send answer from device B to A i get this notifier :
javax.bluetooth.BluetoothExeption: unable to swithc master
it is becouse this part of code :
StreamConnection conn =(StreamConnection) Connector.open(connString);
now what should i do for slove this probleam ?
thanks
Client class :
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.*;
class Client implements CommandListener, Runnable {
Display display;
String msg;
Midlet midlet;
Form frm;
Command cmdBack = new Command("Back", Command.BACK, 1);
LocalDevice local = null;
DiscoveryAgent agent = null;
Thread thread;
StreamConnection conn = null;
OutputStream out = null;
public Client(String string, Midlet midlet, Display display) {
this.display = display;
this.midlet = midlet;
this.msg = string;
frm = new Form("Send Form");
frm.addCommand(cmdBack);
frm.setCommandListener(this);
thread = new Thread(this);
thread.start();
display.setCurrent(frm);
}
private void doDiscovery() {
try {
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
String connString = agent.selectService(new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false), ServiceRecord.NOAUTHENTICATE_NOENCRYPT, true);
if (connString != null) {
try {
conn = (StreamConnection) Connector.open(connString);
} catch (IOException ex) {
frm.append(ex.toString() + "1");
}
try {
out = conn.openOutputStream();
} catch (IOException ex) {
frm.append(ex.toString() + "2");
}
try {
out.write(msg.getBytes());
} catch (IOException ex) {
frm.append(ex.toString() + "3");
}
try {
out.close();
} catch (IOException ex) {
frm.append(ex.toString() + "4");
}
try {
conn.close();
} catch (IOException ex) {
frm.append(ex.toString() + "5");
}
System.out.println("Message sent currectly");
} else {
frm.append("connString == null");
}
} catch (BluetoothStateException ex) {
frm.append(ex.toString() + "6");
}
}
public void commandAction(Command c, Displayable d) {
if (c == cmdBack) {
display.setCurrent(midlet.tb);
}
}
public void run() {
doDiscovery();
}
}
Server Class :
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.lcdui.*;
class Server implements Runnable {
Display display;
String msg;
Midlet midlet;
Thread thread;
private boolean endRecive = false;
public Server(Midlet midlet, Display display) {
this.display = display;
this.midlet = midlet;
thread = new Thread(this);
thread.start();
}
private void recive() {
try {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
midlet.tb.setString("Failed to change to the discoverable mode");
return;
}
StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + "86b4d249fb8844d6a756ec265dd1f6a3");
StreamConnection conn = notifier.acceptAndOpen();
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
midlet.tb.delete(0, midlet.tb.size());
midlet.tb.setString(out.toString());
in.close();
conn.close();
notifier.close();
endRecive = true;
thread.interrupt();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public void run() {
while (endRecive != true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
recive();
}
}
}
and midlet :
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
public class Midlet extends MIDlet implements CommandListener {
Display display = Display.getDisplay(this);
TextBox tb = new TextBox("Chat", null, 100, TextField.ANY);
Command cmdSend = new Command("Send", Command.OK, 1);
Command cmdRecive = new Command("Recive", Command.OK, 2);
Command cmdClear = new Command("Clear...", Command.OK, 3);
Command cmdExit = new Command("Exit", Command.EXIT, 4);
public void startApp() {
tb.addCommand(cmdSend);
tb.addCommand(cmdRecive);
tb.addCommand(cmdClear);
tb.addCommand(cmdExit);
tb.setCommandListener(this);
display.setCurrent(tb);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
destroyApp(true);
} else if (c == cmdClear) {
tb.delete(0, tb.size());
} else if (c == cmdSend && tb.getString().length() > 0) {
new Client(tb.getString(), this, display);
} else if (c == cmdRecive) {
tb.setString("Wait ...");
new Server(this, display);
}
}
}

error in java (CameraMIDlet)

i have the following code which is giving me error:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class DeviceClientCOMM implements DiscoveryListener, CommandListener {
static final boolean DEBUG = false;
static final String DEBUG_address = "0013FDC157C8"; // N6630
protected UUID uuid = new UUID(0x1101); // serial port profile
protected int inquiryMode = DiscoveryAgent.GIAC; // no pairing is needed
protected int connectionOptions = ServiceRecord.NOAUTHENTICATE_NOENCRYPT;
protected int stopToken = 255;
private Command backCommand = new Command("Back", Command.BACK, 1);
protected Form infoArea = new Form("Bluetooth Client");
protected Vector deviceList = new Vector();
private CameraMIDlet mymidlet;
private byte[] imag;
public DeviceClientCOMM(CameraMIDlet m, byte[] imag) {
mymidlet = m;
this.imag = imag;
infoArea.setCommandListener(this);
infoArea.addCommand(backCommand);
try {
startApp();
} catch (MIDletStateChangeException ex) {
ex.printStackTrace();
}
}
protected void startApp() throws MIDletStateChangeException {
makeInformationAreaGUI();
if (DEBUG) // skip inquiry in debug mode
{
startServiceSearch(new RemoteDevice(DEBUG_address) {
});
} else {
try {
startDeviceInquiry();
} catch (Throwable t) {
log(t);
}
}
}
private void startDeviceInquiry() {
try {
log("Start inquiry method - this will take few seconds...");
DiscoveryAgent agent = getAgent();
agent.startInquiry(inquiryMode, this);
} catch (Exception e) {
log(e);
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
log("A device discovered (" + getDeviceStr(btDevice) + ")");
deviceList.addElement(btDevice);
}
public void inquiryCompleted(int discType) {
log("Inquiry compeleted. Please select device from combo box.");
makeDeviceSelectionGUI();
}
private void startServiceSearch(RemoteDevice device) {
try {
log("Start search for Serial Port Profile service from " + getDeviceStr(device));
UUID uuids[] = new UUID[]{uuid};
getAgent().searchServices(null, uuids, device, this);
} catch (Exception e) {
log(e);
}
}
public void servicesDiscovered(int transId, ServiceRecord[] records) {
log("Service discovered.");
for (int i = 0; i < records.length; i++) {
ServiceRecord rec = records[i];
String url = rec.getConnectionURL(connectionOptions, false);
handleConnection(url);
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String msg = null;
switch (respCode) {
case SERVICE_SEARCH_COMPLETED:
msg = "the service search completed normally";
break;
case SERVICE_SEARCH_TERMINATED:
msg = "the service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch()";
break;
case SERVICE_SEARCH_ERROR:
msg = "an error occurred while processing the request";
break;
case SERVICE_SEARCH_NO_RECORDS:
msg = "no records were found during the service search";
break;
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
msg = "the device specified in the search request could not be reached or the local device could not establish a connection to the remote device";
break;
}
log("Service search completed - " + msg);
}
private void handleConnection(final String url) {
Thread echo = new Thread() {
public void run() {
StreamConnection stream = null;
InputStream in = null;
OutputStream out = null;
try {
log("Connecting to server by url: " + url);
stream = (StreamConnection) Connector.open(url);
log("Bluetooth stream open.");
// InputStream in = stream.openInputStream();
out = stream.openOutputStream();
in = stream.openInputStream();
startReadThread(in);
// String stringImage = Base64.encode(imag);
log("Start echo loop.");
out.write(imag);
out.flush();
// out.flush();
// stream.close();
} catch (IOException e) {
log(e);
} finally {
log("Bluetooth stream closed.");
if (out != null) {
try {
out.close();
stream.close();
logSet("Image Transfer done\n----------------\n\nWaiting for results...");
} catch (IOException e) {
log(e);
}
}
}
}
};
echo.start();
}
private void startReadThread(final InputStream in) {
Thread reader = new Thread() {
public void run() {
byte[] s = new byte[512];
//boolean flag = true;
try {
while (true) {
int r = in.read(s);
if (r != -1) {
logSet(new String(s, 0, r));
} else {
break;
}
Thread.sleep(200);
}
} catch (Throwable e) {
log(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
};
reader.start();
}
private void makeInformationAreaGUI() {
infoArea.deleteAll();
Display.getDisplay(mymidlet).setCurrent(infoArea);
}
private void makeDeviceSelectionGUI() {
final List devices = new List("Select a device", List.IMPLICIT);
for (int i = 0; i < deviceList.size(); i++) {
devices.append(
getDeviceStr((RemoteDevice) deviceList.elementAt(i)), null);
}
devices.setCommandListener(new
CommandListener( ) {
public void commandAction(Command arg0,
Displayable arg1)
{
makeInformationAreaGUI();
startServiceSearch((RemoteDevice) deviceList.elementAt(devices.getSelectedIndex()));
}
});
Display.getDisplay(mymidlet).setCurrent(devices);
}
synchronized private void log(String msg) {
infoArea.append(msg);
infoArea.append("\n\n");
}
synchronized private void logSet(String msg) {
infoArea.deleteAll();
infoArea.append(msg);
infoArea.append("\n\n");
}
private void log(Throwable e) {
log(e.getMessage());
}
private DiscoveryAgent getAgent() {
try {
return LocalDevice.getLocalDevice().getDiscoveryAgent();
} catch (BluetoothStateException e) {
throw new Error(e.getMessage());
}
}
private String getDeviceStr(RemoteDevice btDevice) {
return getFriendlyName(btDevice) + " - 0x" + btDevice.getBluetoothAddress();
}
private String getFriendlyName(RemoteDevice btDevice) {
try {
return btDevice.getFriendlyName(false);
} catch (IOException e) {
return "no name available";
}
}
public void commandAction(Command arg0, Displayable arg1) {
mymidlet.DisplayMainList();
}
}
the errors are
C:\Documents and Settings\admin\My Documents\NetBeansProjects\DeviceClientCOMM\src\DeviceClientCOMM.java:51: cannot find symbol
symbol : class CameraMIDlet
location: class DeviceClientCOMM
private CameraMIDlet mymidlet;
C:\Documents and Settings\admin\My Documents\NetBeansProjects\DeviceClientCOMM\src\DeviceClientCOMM.java:54: cannot find symbol
symbol : class CameraMIDlet
location: class DeviceClientCOMM
public DeviceClientCOMM(CameraMIDlet m, byte[] imag)
You don't have an import for CameraMIDlet, so the compiler doesn't know which class you mean.
Assuming you've got an appropriate classpath entry, you should just be able to add the right import and it should be fine.
Are you sure CameraMIDlet exists for your use though? I can see some sample code in JSR-135, but I'm not sure it's a full API to be used...

Resources