I'm trying to make a multiplayer game, but first i want to try it with a simple scanner and print code
i have two files, "cl.java" is the client , "server.java" is the server.
WHAT AM I TRYING TO DO ?
a client send a message to other client asking for a game
this initial message does not run in my code , i am thinking that i can not use the clientThread.sendText(un + " iWantToPlay"); outside the class ConnectThread
WHAT DO U THINK ?
the error happens on this code:
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
with the oos.writeObject(text);
this is Server.java
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();
public static void main(String[] args) {
new Server();
}
public Server() {
// ServerSocket is only opened once !!!
try {
serverSocket = new ServerSocket(6000);
System.out.println("Waiting on port 6000...");
boolean connected = true;
// this method will block until a client will call me
while (connected) {
Socket singleClient = serverSocket.accept();
// add to the list
ServerThread myThread = new ServerThread(singleClient);
allClients.add(myThread);
myThread.start();
}
// here we also close the main server socket
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServerThread extends Thread {
Socket threadSocket;
String msg;
boolean isClientConnected;
InputStream input;
ObjectInputStream ois;
OutputStream output;
ObjectOutputStream oos; // ObjectOutputStream
public ServerThread(Socket s) {
threadSocket = s;
}
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
input = threadSocket.getInputStream();
ois = new ObjectInputStream(input);
output = threadSocket.getOutputStream();
oos = new ObjectOutputStream(output);
// get the user name from the client and store
// it inside thread class for later use
// msg = (String) ois.readObject();
msg = (String) ois.readObject();
for (ServerThread t : allClients)
t.sendText(msg);
isClientConnected = true;
System.out.println("connect ... ");
// System.out.println(msg);
// for(ServerThread t:allClients)
// t.sendText("User has connected...");
// send this information to all users
// dos.writeUTF(userName + " has connected..");
// for(ServerThread t:allClients)
// t.sendText(msg);
while (isClientConnected) {
try {
msg = (String) ois.readObject();
System.out.println(msg);
for (ServerThread t : allClients)
t.sendText(msg);
} catch (Exception e) {
}
}
// close all resources (streams and sockets)
ois.close();
oos.close();
threadSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
this is the cl.java
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;
static ConnectThread clientThread;
boolean isConnected;
static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
static String un;
static String op = "none";
static int turn = 1;
public static void main(String[] args) {
boolean running = true;
System.out.print("Enter a username: ");
un = scanner.nextLine();
System.out.print("invite or wait ?");
msg = scanner.nextLine();
if (msg.equalsIgnoreCase("invite")) {
System.out.print("Enter an opponent: ");
op = scanner.nextLine();
}
new cl();
if (op.equalsIgnoreCase("amjad")) {
clientThread.sendText(un + " iWantToPlay");
}
}
public String getWord(String line,int i) {
String arr[] = line.split(" ", 2);
return arr[i];
}
public cl() {
connectUser();
}
public void connectUser() {
clientThread = new ConnectThread();
clientThread.start();
}
class ConnectThread extends Thread {
InputStream input;
OutputStream output;
ObjectOutputStream oos;
Socket s;
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
s = new Socket(HOST, PORT);
output = s.getOutputStream();
oos = new ObjectOutputStream(output);
isOnline = true;
isConnected = true;
new ListenThread(s).start();
/* while (isOnline) {
msg = scanner.nextLine();
clientThread.sendText(un + ": " + msg);
}
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ListenThread extends Thread {
Socket s;
InputStream input;
ObjectInputStream ois;
public ListenThread(Socket s) {
this.s = s;
try {
input = s.getInputStream();
ois = new ObjectInputStream(input);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while (isConnected) {
try {
final String inputMessage = (String) ois.readObject();
String user;
user = getWord(inputMessage,1);
String message = getWord(inputMessage,2);
/*if (!user.equals(un)) {
System.out.println(inputMessage);
}*/
if (message.equalsIgnoreCase("iwanttoplay")) {
System.out.println(user + " wants to play, accept? y\n");
msg = scanner.nextLine();
clientThread.sendText(un + " " + msg);
}
else if (message.equalsIgnoreCase("yesiwanttoplay")) {
System.out.println(un + " accepted invitation, " + un + " against " + user);
turn = 1;
play(un,user);
}
else if (message.equalsIgnoreCase("noidontwanttoplay")) {
System.out.println(user + " denied invitation.. ");
}
else if (message.equalsIgnoreCase("x") || message.equalsIgnoreCase("o")) {
System.out.println(user + " played .. " + message);
turn = 1;
play(un,user);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void play(String me, String him) {
if (turn == 1) {
System.out.println("your turn,... play a move..x or o ..");
msg = scanner.nextLine();
clientThread.sendText(un + " " + msg);
turn = 2;
}
}
}
this is my error
Exception in thread "main" java.lang.NullPointerException
at cl$ConnectThread.sendText(cl.java:68)
at cl.main(cl.java:38)
xception in thread "main" java.lang.NullPointerException
at cl$ConnectThread.sendText(cl.java:68)
You should be able to figure this out yourself. The line in question appears to be
oos.writeObject(text);
and so clearly oos is null at that point.
You don't need StackOverflow to sort out NullPointerExceptions.
Related
client connection works (I use telnet), but nothing happens when I write a message with any client - even the condition with empty char (for disconnection).
I don't understand why. I get capacity and port with args[], and I start the server.
I already tested a simpler version with just a server which can handle one by one client, and it works.
public class EchoClient extends Thread {
EchoServerForPool serv;
BufferedReader inchan;
DataOutputStream outchan;
Socket socket;
int port;
public EchoClient(EchoServerForPool serv) {
// TODO Auto-generated constructor stub
this.serv = serv;
}
#Override
public void run() {
// TODO Auto-generated method stub
Socket s;
while (true) {
synchronized (this.serv) {
if (this.serv.stillWaiting() == 0) {
try {
this.serv.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
s = this.serv.removeFirstSocket();
serv.newConnect();
}
try {
inchan = new BufferedReader(new InputStreamReader(s.getInputStream()));
outchan = new DataOutputStream(s.getOutputStream());
String message = inchan.readLine();
if (message.equals("")) {
System.out.println("fin de connection");
break;
}
outchan.writeChars(message + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
s.close();
synchronized (serv) {
serv.clientLeft();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class EchoServerForPool extends Thread {
ArrayList<EchoClient> clients;
ArrayList<Socket> sockets;
Socket client;
int nbLocalhost = 0;
int capacity, port, nbConnectedClient, nbWaitingSocket;
public EchoServerForPool(int capacity, int port) {
// TODO Auto-generated constructor stub
this.capacity = capacity;
this.port = port;
clients = new ArrayList<EchoClient>(capacity);
sockets = new ArrayList<Socket>();
for (int i = 0; i < clients.size(); i++) {
EchoClient ec_i = new EchoClient(this);
clients.add(ec_i);
ec_i.start();
}
}
public Socket removeFirstSocket() {
Socket res = sockets.get(0);
sockets.remove(0);
return res;
}
public void newConnect() {
nbConnectedClient++;
nbWaitingSocket--;
}
public int stillWaiting() {
return nbWaitingSocket;
}
public void clientLeft() {
nbConnectedClient--;
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket serv = new ServerSocket(this.port);
while (true) {
this.client = serv.accept();
synchronized (this) {
nbLocalhost++;
System.out.println(client.getInetAddress().getHostName() + "-" + nbLocalhost + " connected");
sockets.add(client);
nbWaitingSocket++;
notify();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class EchoPoolThread {
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
int capacity = Integer.parseInt(args[1]);
EchoClient.EchoServerForPool serveur = new EchoClient.EchoServerForPool(capacity, port);
System.out.println("start server");
serveur.start();
}
}
EDIT : the problem was I iterate with clients.size() which is 0 instead of capacity, for fill my clients list....
I've refactored your code a little bit to have a working solution. You can work from there to create a pool, right now the number of clients isn't limited.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* #author Gianlu
*/
public class Main {
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
int capacity = Integer.parseInt(args[1]);
EchoServerForPool serveur = new EchoServerForPool(capacity, port);
System.out.println("start server");
serveur.start();
}
public static class EchoServerForPool extends Thread {
private final int port;
private final ExecutorService executor;
private final ArrayList<EchoClient> clients;
private int nbLocalhost = 0;
public EchoServerForPool(int capacity, int port) {
this.port = port;
clients = new ArrayList<>();
executor = Executors.newFixedThreadPool(capacity);
}
#Override
public void run() {
try {
ServerSocket serv = new ServerSocket(this.port);
while (true) {
Socket socket = serv.accept();
EchoClient client = new EchoClient(this, socket);
executor.submit(client);
clients.add(client);
nbLocalhost++;
System.out.println(socket.getInetAddress().getHostName() + "-" + nbLocalhost + " connected");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void terminated(EchoClient client) {
clients.remove(client);
}
}
public static class EchoClient implements Runnable {
private final EchoServerForPool pool;
private final Socket socket;
private final BufferedReader inchan;
private final DataOutputStream outchan;
public EchoClient(EchoServerForPool pool, Socket socket) throws IOException {
this.pool = pool;
this.socket = socket;
this.inchan = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.outchan = new DataOutputStream(socket.getOutputStream());
}
#Override
public void run() {
try {
while (true) {
String message = inchan.readLine();
if (message.equals("")) {
System.out.println("fin de connection");
break;
}
outchan.writeChars(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
pool.terminated(this);
}
}
}
So my question is when a socket connects is it possible to create two datainputstreams which both reference to 1 socket inputstream. I would like to print out text and text2 but this does not work.
Client code
public static void main(String[] args) {
new Sender();
}
public Sender() {
try {
Socket sock = new Socket("127.0.0.1",1337);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeUTF("Test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server code
public static void main(String[] args) {
new Listen();
}
public Listen() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
try {
ServerSocket serversocket = new ServerSocket(1337);
while(true) {
Socket socket = serversocket.accept();
System.out.println(socket.getPort() + ": " + socket.getInetAddress().getHostAddress());
DataInputStream input = new DataInputStream(socket.getInputStream());
DataInputStream input2 = new DataInputStream(socket.getInputStream());
String text = input.readUTF();
String text2 = input2.readUTF();
if(text != null) {
System.out.println(text);
}
if(text2 != null) {
System.out.println(text2);
}
//socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error");
}
You need a loop, that terminates on EOFException. And don't write code like this. Code that depends on the success of code in a prior try block should be inside that try block.
input = new DataInputStream(socket.getInputStream());
while(!formclosed) {
try {
String addtext = input.readUTF();
addtext = formatText(addtext);
logarea.setText(logarea.getText() + addtext);
} catch (EOFException e) {
System.out.println("Client has disconnected.");
return;
}
}
// any other IOException should be treated as an error
This should run as a background thread, not when you press a button.
I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?
For the chat program in android side I am sending message via DataInput stream as
Socket sck = new Socket();
sck.connect(new InetAddress("192.168.1.91",1500),2000);
if(sck.isConnected())
{
DataOutputStream os = new DataOutputStream(sck.getOutputStream());
os.writeUTf(msg);
System.out.println("Message sent");
}
and on the Server side My code is
ServerSocket serv = new ServerSocket(1500);
Socket sock = serv.accept();
DataInputStream is = new DataInputStream(sock.getInputStream);
String ans = is.readUTF();
System.out.println("Got"+ans);
But on server side it seems it does not received anything and still waiting for the message. But on client side It shows message sent.
Here is my full code.
package in.prasilabs.eagleeye;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class EagleClient extends Thread
{
public int ret = 0;
private String ip;
private int port;
private Socket sck;
private boolean estb = false;
private DataInputStream is;
private DataOutputStream os;
private String rmsg = null;
private String msg;
private String username;
private String password;
public String reply;
Data dt = new Data();
public EagleClient()
{
}
public EagleClient(String ip, int port, String username, String password)
{
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
}
public void run()
{
establish();
if(estb == true)
{
sendInfo(username,password);
}
}
public void establish()
{
int time_out = 2000;
try
{
System.out.println("trying to connect");
sck = new Socket();
sck.connect(new InetSocketAddress(dt.getIp(),dt.getServerPort()),time_out);
estb = true;
System.out.println("Established");
}
catch (UnknownHostException e)
{
ret =0;
e.printStackTrace();
}
catch (IOException e)
{
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
if(estb == true)
{
try {
is = new DataInputStream(sck.getInputStream());
os = new DataOutputStream(sck.getOutputStream());
dt.setOS(os);
dt.setIS(is);
System.out.println("Messages are ready to send");
} catch (IOException e)
{
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendInfo(String user,String password)
{
Data dt = new Data();
is = dt.getIS();
os = dt.getOS();
String drport = Integer.toString(dt.getdrPort());
try {
os.writeUTF("logn");
System.out.println("Sending user info");
os.writeUTF(dt.getUsername());
os.writeUTF(dt.getPassword());
os.writeUTF(drport);
reply = is.readUTF();
if(reply.equals("success"))
dt.setLoginStatus(true);
else
dt.setLoginStatus(false);
System.out.println("ACk recieved");
} catch (IOException e) {
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int sendMessage(String msg)
{
Data dt = new Data();
os = dt.getOS();
is = dt.getIS();
this.msg = msg;
try {
os.writeUTF(msg);
System.out.println("Client :" +msg);
recieveMessage();
} catch (IOException e) {
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void recieveMessage()
{
try {
System.out.println("Trying to get acknowledgement");
sck.setSoTimeout(2000);
rmsg = is.readUTF();
if(rmsg.equals(msg))
{
System.out.println("Ack recvd" +rmsg);
ret = 1;
}
else if(!msg.equalsIgnoreCase(rmsg))
{
//sendMessage();
Thread.sleep(100);
System.out.println("Retrying");
rmsg = is.readUTF();
System.out.println("Ack recvd" +rmsg);
ret = 1;
}
else
{
System.out.println("Message not recieved");
ret = 0;
}
} catch (IOException e) {
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
Try to use something like this:
String message = "";
while (!"end".equals(message)) {
if (is.available() != 0) {
message = dis.readUTF();
System.out.println(message);
}
}
I checked this - working. Server must be up before client will send message.
This question already has answers here:
Closed 13 years ago.
Duplicate of Implementation of Xmodem Protocol in Java
I've got to implement the xmodem protocol to receive a file from a target device. For that, I have to request the file, then for every 128-byte packet received, I have to send an acknowledgment. My problem is when I open an outputstream to request the file, it will write but after that I can't write again to the outputstream. What is the problem I'm not getting?
package writeToPort;
import java.awt.Toolkit;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JOptionPane;
import constants.Constants;
public class Flashwriter implements Runnable, SerialPortEventListener {
Enumeration portList;
CommPortIdentifier portId;
String messageString = "\r\nFLASH\r\n";
SerialPort serialPort;
OutputStream outputStream,outputStream2;
InputStream inputStream;
//Thread readThread;
String one, two;
String test = "ONLINE";
String[] dispArray = new String[1];
int i = 0;
Thread readThread;
byte[] readBufferArray;
int numBytes;
String response;
FileOutputStream out;
final int FLASH = 1, FILENAME = 2;
int number;
File winFile;
public static void main(String[] args) throws IOException {
Flashwriter sm = new Flashwriter();
sm.FlashWriteMethod();
}
public void FlashWriteMethod() throws IOException {
portList = CommPortIdentifier.getPortIdentifiers();
winFile = new File("D:\\testing\\out.FLS");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM2")) {
// if (portId.getName().equals("/dev/term/a")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp",
1000);
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort
.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// serialPort.disableReceiveTimeout();
// outputStream.write(messageString.getBytes());
// sendRequest("/r/n26-02-08.FLS/r/n");
number = FLASH;
sendRequest(number);
} catch (UnsupportedCommOperationException e) {
}
}
}
}
}
public void serialEvent(SerialPortEvent event) {
SerialPort port = (SerialPort) event.getSource();
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
try {
while (inputStream.available() > 0) {
numBytes = inputStream.available();
readBufferArray = new byte[numBytes];
// int readtheBytes = (int) inputStream.skip(2);
int readBytes = inputStream.read(readBufferArray);
one = new String(readBufferArray);
System.out.println("readBytes " + one);
if (one.indexOf("FLASH_") > -1 & !(one.indexOf("FLASH_F") > -1)) {
System.out.println("got message");
response = "FLASH_OK";
// JOptionPane.showMessageDialog(null,
// "ONLINE",
// "Online Dump",
// JOptionPane.INFORMATION_MESSAGE);
// Toolkit.getDefaultToolkit().beep();
// outputStream.write("\r\nONLINEr\n".getBytes());
// outputStream.flush();
// outputStream.write("/r/n26-02-08.FLS/r/n".getBytes());
number = FILENAME;
sendRequest(number);
}
out = new FileOutputStream(winFile, true);
out.write(readBufferArray);
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
readBufferArray = null;
// break;
}
// try {
// int c;
// while((c = inputStream.read()) != -1) {
// out.write(c);
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// // readBufferArray=null;
// break;
// }
// if (inputStream != null)
// try {
// inputStream.close();
// if (port != null) port.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
//
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void dispPacket(String packet) {
if (response == "FLASH_OK") {
System.out.println("disppacket " + packet);
} else {
System.out.println("No resust");
}
}
public void sendRequest(int num) {
switch (num) {
case FLASH:
try {
// outputStream = serialPort.getOutputStream();
outputStream.write("AT".getBytes());
// outputStream.write("\r\n26-02-08.FLS\r\n".getBytes());
System.out.println("Flash switch");
// outputStream.close();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
case FILENAME:
try {
//outputStream =(serialPort.getOutputStream());
outputStream.write("\r\nSUNSHINE\\06-03-09.FLS\r\n".getBytes());
System.out.println("File name");
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Perhaps the streams are blocking.
Java nio has channels that do not block. Try using one of those.
Here's a sample of reading a file with nio. I'm not sure if the same applies for you or not.
I hope it helps.