inStream.read in serial communications - java

I'm trying to monitor temperature from a remote device using a TC65 modem. To request, 'C' has to be sent with a carriage return at the end. The problem is, I only get this on my phone: "This is test sms. The current temperature is " without the temperature I requested. I tried communicating with the thermostat using HyperTeminal without a problem.
Could you help me with instream.read? The output is double (accurate by two decimals).
Here's my code. Thanks.
package example.rs232demo;
import javax.microedition.midlet.*;
import java.io.*;
import javax.microedition.io.*;
import com.siemens.icm.io.*;
public class RS232Demo extends MIDlet {
CommConnection commConn;
InputStream inStream;
OutputStream outStream;
private ATCommand ATC;
public static String phone = "+97455781868";
public static String message = "This is test sms.";
/**
* RS232Demo - default constructor
*/
public RS232Demo() {
//System.out.println("RS232Demo: Constructor");
//System.out.println("Available COM-Ports: " + System.getProperty("microedition.commports"));
try {
//String strCOM = "comm:com0;blocking=on;baudrate=115200";
String strCOM = "comm:com0;blocking=on;baudrate=9600;bitsperchar=7;parity=even";
commConn = (CommConnection)Connector.open(strCOM);
//System.out.println("CommConnection(" + strCOM + ") opened");
//System.out.println("Real baud rate: " + commConn.getBaudRate());
inStream = commConn.openInputStream();
outStream = commConn.openOutputStream();
//System.out.println("InputStream and OutputStream opened");
} catch(IOException e) {
//System.out.println(e);
notifyDestroyed();
}
}
/**
* startApp()
*/
public void startApp() throws MIDletStateChangeException {
int ch = 0;
//System.out.println("RS232Demo: startApp");
//System.out.println("Looping back received data, leave with 'Q'...");
try {
outStream.write('C');
outStream.write('\r');
ch = inStream.read();
} catch(IOException e) {
//System.out.println(e);
}
try
{
this.ATC = new ATCommand(false);
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
}
send_Simple_SMS(phone, message, ch);
try
{
this.ATC.release();
}
catch(ATCommandFailedException ex)
{
ex.printStackTrace();
}
destroyApp(true);
}
public void pauseApp() {
//System.out.println("RS232Demo: pauseApp()");
}
public int send_Simple_SMS(String phone, String message, int ch)
{
int res = -1;
String AT = "";
String response = "";
synchronized (System.out)
{
}
if(ATC==null){return res;}
try
{
synchronized (ATC)
{
ATC.send("AT+CMGF=1\r");
ATC.send("AT+IFC=1,1\r");
response = "";
response = ATC.send("AT+CMGS=?\r");
if (response.trim().indexOf("OK") < 0)
{
return res;
}
response = ATC.send("AT+CMGS=" + phone + '\r' + '\n');
//System.out.println("Sending.");
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
//System.out.println("Sent.");
if (response.trim().indexOf("OK") >= 0)
{
res = 0;
}
ATC.notifyAll();
}
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
res = -1;
}
return res;
}
public void destroyApp(boolean cond) {
//System.out.println("RS232Demo: destroyApp(" + cond + ")");
try {
inStream.close();
outStream.close();
commConn.close();
//System.out.println("Streams and connection closed");
} catch(IOException e) {
//System.out.println(e);
}
notifyDestroyed();
}
}

Problem is here:
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
It converts ch to corrensponding character, not to number string.
Try the following:
response = ATC.send(message + "The current temperature is " + ch + '\032');

Related

Why do I get zero-filled messages from dynamic queue

A requester is sending messages over a normal queue to a responder, indicating a dynamic queue it created as a reply queue. The responder puts these same messages on the reply queue. The responder retrieves all messages correctly.
For each message sent the requester obtains a message from the reply queue, but its body is filled with zeroes. Both programs are written in Java, using com.ibm.mq.allclient-9.2.2.0.jar. When I wrote the same in JavaScript with Node.js and ibmmq for node, everything worked fine.
Requester.java:
package com.hellerim.imq.comm.requester;
import static com.ibm.mq.constants.CMQC.MQENC_INTEGER_NORMAL;
import static com.ibm.mq.constants.CMQC.MQFMT_STRING;
import static com.ibm.mq.constants.CMQC.MQGMO_FAIL_IF_QUIESCING;
import static com.ibm.mq.constants.CMQC.MQGMO_NO_SYNCPOINT;
import static com.ibm.mq.constants.CMQC.MQGMO_NO_WAIT;
import static com.ibm.mq.constants.CMQC.MQGMO_WAIT;
import static com.ibm.mq.constants.CMQC.MQMT_REQUEST;
import static com.ibm.mq.constants.CMQC.MQOO_FAIL_IF_QUIESCING;
import static com.ibm.mq.constants.CMQC.MQOO_INPUT_EXCLUSIVE;
import static com.ibm.mq.constants.CMQC.MQOO_OUTPUT;
import static com.ibm.mq.constants.CMQC.MQPMO_NO_SYNCPOINT;
import static com.ibm.mq.constants.CMQC.MQRC_NO_MSG_AVAILABLE;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import io.netty.util.CharsetUtil;
import net.jcip.annotations.GuardedBy;
public class Requester
{
private static final int WAIT_WHILE_EMPTY = 100; // ms
private static int MAX_MILLIS_BETWEEN_REQUESTS = 100;
private static int LONG_WIDTH_IN_HEX_CHARS = 16;
private static final Charset charset = CharsetUtil.ISO_8859_1;
private MQQueueManager qMgr;
private final MQQueue requestQueue;
private final String queueNamePattern = "TEST.SESSION.*";
private String replyQueueName;
private final MQQueue replyQueue;
private final MQGetMessageOptions getOptions = new MQGetMessageOptions();
private static final String MQ_MANAGER = "MY_QM";
private static final String REQUEST_QUEUE = "TEST.REQUESTS";
private static final String MODEL_QUEUE = "TEST.SESSION.MODEL";
final private Object locker = new Object();
#GuardedBy("this")
boolean stopped = false;
int rcvd = 0;
public static void main(String[] args) {
try {
Requester rq = new Requester(MQ_MANAGER, REQUEST_QUEUE, MODEL_QUEUE);
List<String> poem = writePoem();
Random requestIds = new Random();
Random delays = new Random(1000);
int cnt = 0;
int position = 0;
for (int i = 0; i < 50; ++i) {
if (i == poem.size()) {
int requestId = requestIds.nextInt(99999) + 1;
String text = poem.stream().collect(Collectors.joining("\n"));
String request = appRequestFrom(text, requestId);
rq.write(request);
System.out.println("Requester: sent request no " + (++cnt) + " - " + requestId);
}
position %= poem.size();
String line = poem.get(position);
int requestId = requestIds.nextInt(99999) + 1;
String request = appRequestFrom(line, requestId);
rq.write(request);
System.out.println("Requester: sent request no " + (++cnt) + " - " + requestId);
position++;
try {
Thread.sleep((long) Math.ceil((Math.pow(
delays.nextDouble(), 4) * MAX_MILLIS_BETWEEN_REQUESTS) + 1));
} catch (InterruptedException e) {
// ignore
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// ignore
}
rq.close();
} catch (MQException e) {
e.printStackTrace();
}
}
public Requester(String mqManagerName, String requestQueueName, String modelQueueName) throws MQException {
super();
System.out.println("Requester: establishing mq session (mq manager: " + mqManagerName +
"/ request queue: " + requestQueueName + " / model queue: " + modelQueueName +")");
qMgr = new MQQueueManager(mqManagerName);
// get request queue
int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING;
requestQueue = qMgr.accessQueue(requestQueueName, openOptions);
// get dynamic reply queue
int inputOptions = MQOO_INPUT_EXCLUSIVE + MQOO_FAIL_IF_QUIESCING;
replyQueue = new MQQueue(qMgr,
modelQueueName,
inputOptions,
"",
queueNamePattern,
"");
replyQueueName = replyQueue.getName();
System.out.println("Requester: created temporary reply queue " + replyQueueName);
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_NO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
// catch-up (for those replies not retrieved after a request was put)
Executors.newSingleThreadExecutor().execute(new Runnable() {
#Override
public void run() {
// read options
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
getOptions.waitInterval = WAIT_WHILE_EMPTY;
while(proceed()) {
try {
if (!retrieveMessage(getOptions)) {
try {
Thread.sleep(getOptions.waitInterval);
} catch (InterruptedException e1) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private boolean retrieveMessage(MQGetMessageOptions getOptions) throws IOException {
MQMessage msg = new MQMessage();
try {
msg.clearMessage();
msg.seek(0);
replyQueue.get(msg, getOptions);
System.out.println("Requester: reply no " + ++rcvd + " received - id: " +
Long.parseLong(new String(msg.messageId, Charset.forName("ISO_8859_1")), 16));
byte[] buf = new byte[msg.getDataLength()];
String message = new String(buf, charset);
System.out.println("Requester: message received:\n" + message);
} catch (MQException e) {
if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) {
return false;
}
}
return true;
}
public byte[] write(String message) {
int positionRequestId = 24;
int endIndex = positionRequestId + 16;
CharSequence requestId = message.substring(positionRequestId, endIndex);
StringBuffer sb = new StringBuffer("00000000");
sb.append(requestId);
byte[] id = sb.toString().getBytes(charset);
MQMessage mqMsg = new MQMessage();
mqMsg.characterSet = 819;
mqMsg.encoding = MQENC_INTEGER_NORMAL;
mqMsg.format = MQFMT_STRING;
mqMsg.messageType = MQMT_REQUEST;
mqMsg.messageId = id;
mqMsg.correlationId = id;
mqMsg.replyToQueueName = replyQueueName;
try {
mqMsg.writeString(message);
mqMsg.seek(0);
MQPutMessageOptions pmo = new MQPutMessageOptions();
pmo.options = MQPMO_NO_SYNCPOINT;
requestQueue.put(mqMsg, pmo);
} catch (IOException e) {
e.printStackTrace();
} catch (MQException e) {
e.printStackTrace();
}
// try to read from reply queue fail immediately
try {
retrieveMessage(getOptions);
} catch (IOException e) {
e.printStackTrace();
}
return id;
}
public void close() {
stop();
try {
Thread.sleep(2 * WAIT_WHILE_EMPTY);
} catch (InterruptedException e1) {
// ignore
}
try {
if (requestQueue != null) {
requestQueue.close();
}
if (qMgr != null) {
qMgr.disconnect();
}
} catch (MQException e) {
// ignore
}
}
public boolean proceed() {
synchronized(locker) {
return !stopped;
}
}
public void stop() {
synchronized(locker) {
stopped = true;
}
}
private static List<String> writePoem() {
List<String> poem = new ArrayList<>();
poem.add("Das Nasobem");
poem.add("von Joachim Ringelnatz");
poem.add("");
poem.add("Auf seiner Nase schreitet");
poem.add("einher das Nasobem,");
poem.add("von seineme Kind begleitet -");
poem.add("es steht noch nicht im Brehm.");
poem.add("");
poem.add("Es steht noch nicht im Meyer");
poem.add("und auch im Brockhaus nicht -");
poem.add("es tritt aus meiner Leier");
poem.add("zum ersten Mal ans Licht.");
poem.add("");
poem.add("Auf seiner Nase schreitet");
poem.add("- wie schon gesagt - seitdem");
poem.add("von seinem Kind begleitet");
poem.add("einher das Nasobem.");
poem.add("");
poem.add("");
return poem;
}
private static String iToHex(int num, int places) {
StringBuilder sb = new StringBuilder();
char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
for (int i = 0; i < places; ++i) {
sb.append(digits[num % places]);
num /= places;
}
return sb.reverse().toString();
}
private static String iToHex(int num) {
return iToHex(num, LONG_WIDTH_IN_HEX_CHARS);
}
private static String appRequestFrom(String msgBody, int requestId) {
int headerLength = 72;
// includes message body length field here!
int bodyLength = msgBody.length();
StringBuilder sb = new StringBuilder();
sb.append("GHI "); // magic
sb.append("1"); // version major
sb.append("0"); // version minor
sb.append("0"); // flags
sb.append("1"); // app message type SYNCHRONOUS REQUEST
sb.append(iToHex(headerLength + bodyLength)); // message length
sb.append(iToHex(requestId)); // request id
sb.append(iToHex(0)); // timeout
sb.append(iToHex(bodyLength)); // message body length
sb.append(msgBody); // message body
return sb.toString();
}
}
Responder.java:
package com.hellerim.imq.comm.responder;
import static com.ibm.mq.constants.CMQC.*;
import java.io.EOFException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import io.netty.util.CharsetUtil;
import net.jcip.annotations.GuardedBy;
public class Responder
{
private MQQueueManager qMgr;
private MQQueue requestQueue;
private Map<String, MQQueue> replyQueues = new HashMap<>();
private final Object locker = new Object();
static final private int WAIT_WHILE_EMPTY = 100; // ms
#GuardedBy("locker")
private boolean stopped = false;
Thread fetcherThread = null;
private final static byte MESSAGE_TYPE_REPLY = 52; // '4'
public final static String MQ_MANAGER = "MY_QM";
public final static String REQUEST_QUEUE = "TEST.REQUESTS";
public static void main( String[] args ) throws MQException, IOException
{
System.out.println( "running reponder application" );
try {
new Responder(MQ_MANAGER, REQUEST_QUEUE).start();
} catch(Exception e) {
e.printStackTrace();
}
}
public Responder(String mqManagerName, String requestQueueName) throws MQException {
System.out.println("establishing mq session (mq manager: " + mqManagerName +
" / request queue: " + requestQueueName + ")");
qMgr = new MQQueueManager(mqManagerName);
int openOptions = MQOO_INPUT_SHARED + MQOO_FAIL_IF_QUIESCING;
requestQueue = qMgr.accessQueue(requestQueueName, openOptions);
}
public MQQueue getReplyQueue(String replyQueueName) throws MQException {
if (replyQueues.containsKey(replyQueueName)) {
return replyQueues.get(replyQueueName);
}
int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING;
MQQueue replyQueue = qMgr.accessQueue(replyQueueName, openOptions);
replyQueues.put(replyQueueName, replyQueue);
System.out.println("Responder: opened dynamic reply queue");
return replyQueue;
}
private void start() throws IOException {
Runnable fetcher = new Runnable() {
#Override
public void run() {
int cnt = 0;
while(proceed()) {
MQMessage msg = new MQMessage();
try {
//msg.clearMessage();
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
getOptions.waitInterval = WAIT_WHILE_EMPTY;
requestQueue.get(msg, getOptions);
System.out.println("Responder: message no " + ++cnt + " received");
MQQueue replyQueue = null;
try {
replyQueue = getReplyQueue(msg.replyToQueueName);
} catch(MQException e) {
if (e.completionCode == MQCC_FAILED && e.reasonCode == MQRC_UNKNOWN_OBJECT_NAME) {
// dynamic reply queue does not exist any more => message out of date
continue;
}
throw e;
}
// set message type for reply
if (msg.getDataLength() < 56) {
System.out.println("invalid message:");
System.out.println(Msg2Text(msg));
continue;
}
System.out.println(Msg2Text(msg));
int typePosition = 7;
msg.seek(typePosition);
msg.writeByte(MESSAGE_TYPE_REPLY);
msg.seek(0);
String text = Msg2Text(msg);
MQMessage msgOut = new MQMessage();
msgOut.characterSet = 819;
msgOut.encoding = MQENC_INTEGER_NORMAL;
msgOut.format = MQFMT_STRING;
msgOut.messageType = MQMT_REPLY;
msgOut.messageId = msg.messageId;
msgOut.correlationId = msg.correlationId;
msgOut.seek(0);
msgOut.writeString(text);
msgOut.seek(0);
System.out.println(text);
// System.out.println("Responder: message received");
MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults, same
pmo.options = MQPMO_NO_SYNCPOINT;
replyQueue.put(msgOut, pmo);
System.out.println("Responder: message no " + cnt + " returned");
} catch (MQException e) {
if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) {
; // NOOP
} else {
try {
msg.seek(0);
System.out.println(msg);
} catch (EOFException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
e.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
shutdown();
}
};
Thread task = new Thread(fetcher);
task.run();
System.out.print("press <ENTER> to terminate ");
System.in.read();
System.out.println();
synchronized(locker) {
stopped = true;
}
try {
task.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String Msg2Text(MQMessage msg) {
int length;
String text = "";
try {
length = msg.getDataLength();
byte[] buf = new byte[length];
msg.seek(0);
msg.readFully(buf);
text = new String(buf, CharsetUtil.ISO_8859_1);
msg.seek(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
private boolean proceed() {
synchronized(locker) {
return !stopped;
}
}
private void shutdown() {
System.out.print("\nshutting down responder... ");
for (MQQueue queue : replyQueues.values()) {
try {
queue.close();
} catch (MQException e) { }
}
replyQueues.clear();
try {
qMgr.close();
} catch (MQException e) { }
System.out.println("done.");
}
}
Is there any idea what might be wrong?
It looks like you have created a buffer the right size for the message data and printed that, without moving the data into it.
In retrieveMessage:
byte[] buf = new byte[msg.getDataLength()];
String message = new String(buf, charset);
System.out.println("Requester: message received:\n" + message);
You might need to call the readFully (or similar) method to get the data.
If you know that your message payload is text (string) then you can do this:
String msgStr = msg.readStringOfByteLength(msg.getMessageLength());
System.out.println("Requester: message received:\n" + msgStr);

How to fix 'Server sending data faster than client can handle, server freezes'

I'm using a java server to facilitate online multiplayer in my game made with GameMaker Studio, the players will send data to the java server which will process the data and send it to the players. The problem is that when a player with a slow internet connection is not being able to handle the amount of data being send to it, it will cause the server to freeze for all players (the server will no longer process any data send by other players).
I have simulated slow internet speeds by using NetLimiter and setting the download speed of one laptop at 5 kb/s, while maintaining proper speed at other laptops. I have tried to send ACK packets from the java server to the client and if it doesn't respond in 1 second no more data will be send to that client (and eventually the client will be kicked). This has reduced the chance of freezing the server, but it will still happen occasionally.
Main.java
import java.net.Socket;
import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.util.HashMap;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
public class Main
{
static ServerSocket serverSocket_;
static HashMap<String, ServerInformation> servers_;
static int verboseLevel_;
static int threadTimeout_;
static int masterPort_;
static int serverNumber_;
static int socketTimeOut_;
static {
Main.serverSocket_ = null;
Main.servers_ = new HashMap<String, ServerInformation>();
Main.verboseLevel_ = 5;
Main.threadTimeout_ = 10;
Main.masterPort_ = 6510;
Main.serverNumber_ = 1;
Main.socketTimeOut_ = 6000;
}
public static void main(final String[] args) {
try {
setupServerAndCleanup(Main.masterPort_);
while (true) {
handleIncomingConnection();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
static void setupServerAndCleanup(final int port) throws IOException {
(Main.serverSocket_ = new ServerSocket()).setReuseAddress(true);
Main.serverSocket_.bind(new InetSocketAddress(Main.masterPort_));
System.out.println("Server socket up and running on port " + Main.masterPort_);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
if (Main.serverSocket_ != null) {
try {
Main.serverSocket_.close();
System.out.println("Server socket closed, port released");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}));
}
static void handleIncomingConnection() throws IOException {
final Socket clientSocket = Main.serverSocket_.accept();
clientSocket.setSoTimeout(Main.socketTimeOut_);
final ClientThread client = new ClientThread(clientSocket);
client.start();
}
}
ClientThread.java
Case 1 is the part dealing with sending data to the clients, in particular this line:
thread2.out_.print(msg);
If more data is being send than one client can handle the server will freeze for all other clients as well.
import java.util.Iterator;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class ClientThread extends Thread
{
Socket clientSocket_;
String clientIp_;
String serverIp_;
ServerInformation server_;
PrintWriter out_;
BufferedReader in_;
boolean prepareTermination_;
boolean terminated_;
private static final Pattern numberPattern;
static {
numberPattern = Pattern.compile("\\d+");
}
public ClientThread(final Socket sock) {
this.clientSocket_ = sock;
this.clientIp_ = this.clientSocket_.getRemoteSocketAddress().toString();
this.serverIp_ = null;
this.server_ = null;
this.prepareTermination_ = false;
this.terminated_ = false;
}
#Override
public void run() {
try {
this.out_ = new PrintWriter(this.clientSocket_.getOutputStream(), true);
this.in_ = new BufferedReader(new InputStreamReader(this.clientSocket_.getInputStream()));
long lastActionTime = System.currentTimeMillis();
while (true) {
if (this.in_.ready() || System.currentTimeMillis() - lastActionTime >= 1000 * Main.threadTimeout_) {
if (System.currentTimeMillis() - lastActionTime >= 1000 * Main.threadTimeout_) {
//this.logDebugMessage(3, "Thread was killed due to prolonged inactivity (" + Main.threadTimeout_ + " seconds)");
this.terminateThread();
return;
}
final String tempInputLine;
if(((tempInputLine = this.in_.readLine()) == null )){
this.terminateThread(); //end thread
return;
}
else
{
lastActionTime = System.currentTimeMillis();
final String inputLine = tempInputLine.trim();
if (ClientThread.numberPattern.matcher(inputLine).matches()){
final int val = Integer.parseInt(inputLine);
switch (val) {
case 1: { //send data to other players
final int parseCount = Integer.parseInt(this.in_.readLine().trim());
final StringBuilder msg = new StringBuilder();
for (int j = 0; j < parseCount; ++j) {
msg.append(String.valueOf(this.in_.readLine().trim()) + "|");
}
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
thread2.out_.print(msg);
thread2.out_.flush();
}
}
//this.logDebugMessage(5, "Packet for others: '" + msg.toString() + "'");
break;
}
case 2: { //remove game server
//this.logDebugMessage(1, "A game server has been deleted, ip: " + ipServer);
Main.servers_.remove(this.server_.ip_);
this.serverIp_ = null;
for (final ClientThread thread : this.server_.ipToClientThread_.values()) {
thread.prepareTermination_ = true;
}
this.terminateThread();
return;
}
case 3: { //connect new client
final String ipServer = this.in_.readLine().trim();
final String ipClient = this.in_.readLine().trim();
this.logDebugMessage(1, "A client wishes to connect to a server, client: " + ipClient + ", server: " + ipServer);
final ServerInformation info = Main.servers_.getOrDefault(ipServer, null);
if (info == null) {
System.out.println("Connection to the server failed, no such server in the server list");
this.out_.print("*" + 1 + "|" + 1 + "~" + "|");
this.out_.flush();
break;
}
this.server_ = info;
this.server_.ipToClientThread_.put(ipClient, this);
this.logDebugMessage(1, "Connection success");
this.logDebugMessage(5,"Map: " + this.server_.ipToClientThread_);
this.out_.print("*" + 1 + "|" + 2 + "~" + "|");
this.out_.flush();
break;
}
case 4: { //disconnect client
final String ipClient = this.in_.readLine().trim();
this.server_.ipToClientThread_.remove(ipClient);
this.logDebugMessage(1, String.valueOf(ipClient) + " disconnected from the server at " + this.server_.ip_);
this.serverIp_ = null;
this.terminateThread();
return;
}
case 5: { //host create new game
if (Main.serverNumber_ > 1000000) {
Main.serverNumber_ = 10;
}
Main.serverNumber_ += 1;
final String ipServer = Integer.toString(Main.serverNumber_); //unique server number
final String ipHost = this.in_.readLine().trim(); //host
final String name = this.in_.readLine().trim(); //Server name
final String description = this.in_.readLine().trim(); //class
final String servervar1 = this.in_.readLine().trim(); //max players
final String servervar3 = this.in_.readLine().trim(); //current lap
final String servervar4 = this.in_.readLine().trim(); //total laps
final String servervar5 = this.in_.readLine().trim(); //status
final String servervar6 = this.in_.readLine().trim(); //Password
final String servervar7 = this.in_.readLine().trim(); //Online version
final String servervar8 = this.in_.readLine().trim(); //Game server
final long servervar9 = System.currentTimeMillis(); //server creation time
//this.logDebugMessage(1, "A game server has been registered, ip: " + ipServer + ", name: " + name + ", description: " + description + ", servervar1: " + servervar1);
final ServerInformation gameServer = new ServerInformation(name, servervar1, servervar3, servervar4, servervar5, servervar6, servervar7, servervar8, servervar9, ipHost, ipServer, this.clientSocket_, this.out_, this.in_);
gameServer.description_ = description;
gameServer.ipToClientThread_.put(ipHost, this);
this.server_ = gameServer;
Main.servers_.put(ipServer, gameServer);
this.serverIp_ = ipServer;
break;
}
default: {
this.logDebugMessage(0, "Unrecognized case: '" + inputLine + "', " + val);
break;
}
}
}
else if (inputLine.length() > 0) {
this.logDebugMessage(0, "Unformated '" + inputLine + "'");
if (this.server_ != null) {
this.server_.out_.print(inputLine);
this.server_.out_.flush();
}
}
if (this.prepareTermination_) {
this.terminateThread();
return;
}
continue;
}
}
}
}
catch (SocketTimeoutException e) {
e.printStackTrace();
try {
this.terminateThread();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
catch (IOException e3) {
e3.printStackTrace();
try {
this.terminateThread();
}
catch (IOException e4) {
e4.printStackTrace();
}
}
}
//debug messages
void logDebugMessage(final int requiredVerbose, final String msg) {
if (Main.verboseLevel_ >= requiredVerbose) {
System.out.println("[" + this.clientIp_ + "] " + msg);
}
}
//terminate thread
void terminateThread() throws IOException {
if (!this.terminated_) {
if (this.serverIp_ != null) {
Main.servers_.remove(this.serverIp_);
}
this.clientSocket_.close();
this.in_.close();
this.out_.close();
this.logDebugMessage(3, "Cleanup successful");
this.terminated_ = true;
}
}
}
How to avoid the server from freezing if more data is being send to a client than it can handle, so that the server can continue sending data to the other clients?
Edit
So I have tried using ExecutorService, but I must be doing something completely wrong because no data is being send by the java server.
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
thread2.out_.print(msg);
thread2.out_.flush();
}
});
executorService.shutdown();
}
}
It would be great if you could show me how to implement ExecutorService the right way.
If a delay in the client processing doesn't matter, this part should be done in a distinct flow execution for each client :
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
thread2.out_.print(msg);
thread2.out_.flush();
}
For example :
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
new Thread(()-> {
thread2.out_.print(msg);
thread2.out_.flush();
})
.start();
}
}
Note that creating Threads has a cost. Using ExecutorService could be a better idea.

How can i make this use multiple threads as clients - who all perform a task each within the switch statement

How can I make this use multiple threads as clients - who all perform a task each within the switch statement? I would also like the threads to perform these tasks and once they have carried them out they stop (currently these tasks are performed from user input).
There are 3 classes the server, client and developer database - which holds a constructor for the 'developer' objects within an ArrayList in the server. This array list is providing the information which is being passed to the clients upon their specific requests.
Here is my code: Client:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
public class QuoteOfTheDayClient_2 {
static String devName;
static String devSkill;
static Boolean devHire;
static Socket echoSocket = null; // holds the Socket object
static Scanner fromServer = null; // input stream from remote host
static Scanner fromServer1 = null; // input stream from remote host
static PrintWriter toServer = null; // output stream to remote host
static PrintWriter toServer1 = null; // output stream to remote host
static Scanner stdIn = new Scanner(System.in);
static String remoteServer = "localhost"; // are you 'local'?!
//String remoteServer = "193.61.190.96"; // remote host is not 'local'!
static int port;
static String reply;// holds reply from remote host
public static void searchForSkill(String skill) {
toServer.println(1);
String quoteNum = "php"; //Search for a specific coding language -
Specific to the entered parameters
System.out.println("Searching for Skill: " + skill + " in Developer
Database");
toServer.println(quoteNum);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void addDeveloper(String name, String skill,boolean
hire)
{
toServer.println(2);
System.out.println("Add Developer to system ");
stdIn.nextLine(); // flush newline
String quoteString = name;//stdIn.nextLine();
String quoteString1 = skill;//stdIn.nextLine();
boolean quoteString2 = hire;//stdIn.nextLine();
toServer.println(quoteString);
toServer.println(quoteString1);
toServer.println(quoteString2);
fromServer.next();
System.out.println("\nDeveloper entered: " + quoteString + "\n");
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
}
public static void checkAvailability(String developerName) {
try {
toServer.println(3);
System.out.println("Send Developer Name to Find Availability:
");
String quoteDel = developerName;
toServer.println(quoteDel);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
} catch (NoSuchElementException e) {
}
}
public static void hireDeveloper(String name) {
toServer.println(4);
String quoteNum = name; //Search for a specific coding language -
Specific to the entered parameters
System.out.println("Searching for: " + name + " in Developer
Database");
toServer.println(quoteNum);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void printAllDevelopers(){
toServer.println(5);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void clientMenu(){
try {
port = 4444; // 17 for localhost
echoSocket = new Socket(remoteServer, port);
fromServer = new Scanner(echoSocket.getInputStream());
fromServer1 = new Scanner(echoSocket.getInputStream());
toServer = new PrintWriter(echoSocket.getOutputStream(), true);
toServer1 = new PrintWriter(echoSocket.getOutputStream(),
true);
OutputStream os = echoSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
} catch (Exception e) {
System.err.println("Exception: " + e);
System.exit(1);
} // try-catch
String reply;// holds reply from remote host
int command;
String reply1;
String devName="David Blaine";
String devSkill="Java";
System.out.println("Enter command: 1:Search Skill 2:Add
Developer 3:Search Availability 4:Hire Developer 5:Show all
Developers 6:Exit");
command = 0;
command = command+1;
// while (command != 0) {
for(int i=1;i<6;i++) {
command=i;
switch (i) {
case 1: {
// get quote
searchForSkill("PHP");
break;
}
case 2: {
// add quote
addDeveloper("David Blaine", "Java", true);
break;
}
case 3: {
// delete quote
checkAvailability("David Ferguson");
break;
}
case 4: {
hireDeveloper("Thompson");
break;
}
case 5: {
printAllDevelopers();
}
case 6: {
System.exit(6);
}
default:
System.out.println("*** Command not recognised ***");
break;
}
System.out.println("Enter command: 1:Search Skill 2:Add Developer
3:Search Availability 4:Hire Developer 5:Show all Developers
6:Exit");
command = stdIn.nextInt();
//}
}
toServer.println(command);
try {
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
fromServer.close();
toServer.close();
stdIn.close();
}
public static void main(String[] args) throws IOException {
clientMenu();
} // main
} // EchoClient
Server code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class QuoteOfTheDayServer_2 {
private static DeveloperDatabase[] developerList = new
DeveloperDatabase[7];
static DeveloperDatabase temp []=new DeveloperDatabase[7];
static String userAddDevName;
static String userAddCodeSkills;
static Boolean userAddHireAvailability;
static int command;
static List<DeveloperDatabase> list = new
ArrayList<DeveloperDatabase>(){
{
add(new DeveloperDatabase(1,"David Ferguson", "Java",
true));
add(new DeveloperDatabase(2,"Grant Thompson", "Java",
true));
add(new DeveloperDatabase(3,"Craig Jackson", "C++", true));
add(new DeveloperDatabase(4,"Kevin James","C++", true));
add(new DeveloperDatabase(5,"Greg Troupe", "Python",
true));
add(new DeveloperDatabase(6,"James Smith", "Python",
true));
add(new DeveloperDatabase(7,"Jamie Richie", "PHP", true));
add(new DeveloperDatabase(8,"Rory McGrattan", "PHP",
false));
}
};
public static String printJava(){
String message="";
for (int i=0;i<2;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printC(){
String message="";
for (int i=2;i<4;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printPy(){
String message="";
for (int i=4;i<6;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printPHP(){
String message="";
for (int i=6;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static void addDeveloper(String name,String
codeSkill,Boolean hire){
userAddDevName=name;
userAddCodeSkills = codeSkill;
userAddHireAvailability = hire;
System.out.println("*********Adding Developer***********");
System.out.println(userAddDevName+ " has been added to the
system");
list.add(new DeveloperDatabase(9,
userAddDevName,userAddCodeSkills, userAddHireAvailability));
System.out.println(list.get(8));
}//addDeveloper
public static String checkAvail(String clientMessage){
String message="";
for (int i=0;i<list.size();i++){
if
(clientMessage.equalsIgnoreCase(list.get(i).getDeveloperName())) {
message+= list.get(i).toString();
message+="\n";
}
} return message;
}
public static String printAllDevelopers(){
String message="";
for (int i=0;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static void main(String[] args) throws IOException {
// Wrap the standard System.in stream with a Scanner so that
Scanner stdIn = new Scanner(System.in);
Scanner fromClient = null;
PrintWriter toClient = null;
PrintWriter toClient1=null;
int pNum = 4444;
ServerSocket sSocket = null;
Socket cSocket = null;
try {
sSocket = new ServerSocket(pNum);
} catch (IOException e) {
System.out.println("Couldn't listen on port: " + pNum + ";
" +
e);
System.exit(1);
}
// Continuously wait for client; accept them; and send a quote
to
them.
while (true) {
try {
System.out.println("Waiting for client ....");
// Blocking 'accept' i.e. wait for a client
cSocket = sSocket.accept();
System.out.println("Client connected from: " +
cSocket.getInetAddress());
// Set up the output stream for the server, i.e. a
PrintWriter stream
toClient = new PrintWriter(cSocket.getOutputStream(),
true);
toClient1 = new PrintWriter(cSocket.getOutputStream(),
true);
ObjectInputStream ois = new
ObjectInputStream(cSocket.getInputStream());
fromClient = new Scanner(cSocket.getInputStream());
try {
command = fromClient.nextInt();
//fromClient.nextLine();
} catch (InputMismatchException e){
System.out.print("Your selection can only be an
integer!");
}
System.out.println("Received command: " + command + "
from
client at " + cSocket.getInetAddress());
while (command != 0) {
switch (command) {
case 1: // get skills
{
System.out.println("GET skill");
fromClient.nextLine();
String quoteNum =
fromClient.nextLine();//receive from client
if (quoteNum.equalsIgnoreCase("Java")) {
toClient1.println(printJava());
} else if
(quoteNum.equalsIgnoreCase("C++")) {
toClient1.println(printC());
} else if
(quoteNum.equalsIgnoreCase("Python"))
{
toClient.println(printPy());
} else if
(quoteNum.equalsIgnoreCase("PHP")) {
toClient.println(printPHP());
}
else {
toClient.println("No developer with
those
skills found");
}
//
toClient.println(list.equals("Java"));//number -1 for array (0) to
client print
System.out.println("Pushed Developer
number: "
+ quoteNum + " to client at " + cSocket.getInetAddress());
//toClient.println(quotes[quoteNum]); //
return
quote //if "java' { get(0) get(1)
break;
}
case 2: // add quote
{
System.out.println("ADD Developer to
System");
fromClient.nextLine(); // flush newline
String quote = fromClient.next();
fromClient.nextLine();
String quote1 = fromClient.next();
fromClient.nextLine();
boolean quote2 = fromClient.nextBoolean();
toClient.println("The\t*************Developer
has been Added to the Developer Database********");
list.add(new DeveloperDatabase(9, quote,
quote1, quote2));
toClient.println(list.get(8).toString());
//addDeveloper(quote,quote1,quote2);
System.out.println(list.get(8));
//System.out.println("Received quote from
client:" + quote);
quote = quote + "\n\n";
//list.add((quote);
System.out.println("Added Developer: " +
quote);
break;
}
case 3: // Check if Developer is available
{
System.out.println("Check if developer is
Available\n");
fromClient.nextLine();
String quoteNum = fromClient.nextLine();
System.out.println("Checking availability
for:
" + quoteNum);
if (quoteNum.equalsIgnoreCase("Rory
McGrattan")) {
toClient.println("The Developer is not
available for hire");
} else {
toClient.println("The Developer is
available for hire");
}break;
}case 4: {
System.out.println("Hire A Developer");
String quoteNum =fromClient.next();
System.out.println("Client wants to hire:
"+quoteNum);
String message = quoteNum;
for(int i=0;i<list.size();i++){
if
(quoteNum.equalsIgnoreCase(list.get(i).getDeveloperName())){
list.get(i).hireDeveloper();
}//if
}//if
//System.out.println(message);
toClient.println("******* You have Hired:
"+
message+" ********");
break;
}
case 5: {// Print all Developers
String message="";
for (int i=0;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
toClient.println(message);
}
default:
break;
}
try {
//command = fromClient.nextInt();
}catch(InputMismatchException e){
}
System.out.println("Received command: " + command +
"from client at " + cSocket.getInetAddress());
}
// Close all streams
toClient.close();
cSocket.close();
fromClient.close();
stdIn.close();
} catch (IOException e) {
System.out.println("Accept failed: " + pNum + "; " +
e);
System.exit(1);
}
}
} // main
} // QuoteOfTheDayServer_2
DeveloperDatabase code:
public class DeveloperDatabase {
private int id;
private String developerName;
private String codingLanguage;
private boolean freeForHire;
public DeveloperDatabase(){
}
public DeveloperDatabase(int id,String name,String codeSkills,boolean
hire){
this.id = id;
this.developerName = name;
this.codingLanguage=codeSkills;
this.freeForHire=hire;
}
public String toString() {
String message = "\tName: " +developerName;
message += "\n" + "\tCoding Language: "+ codingLanguage+"\n";
if (freeForHire== true) {
message += "\tThe developer is Available! for Hire!\n";
} else {
message += "\tThe developer is not Available for Hire!\n";
}
return message;
}//toString
public boolean getFreeForHire() {
if (freeForHire==true){
System.out.println("The Developer is free to hire!");
}else{
System.out.println("The Developer is not free to hire!");
}
return freeForHire;
}
public String getCodingLanguage() {
return codingLanguage;
}
public void hireDeveloper(){
if (freeForHire==true)
freeForHire = false;
System.out.println(developerName +" is Hired!");
}
public String getDeveloperName() {
return developerName;
}
public static void main(String[] args) {
}//main
}//class
you could use something like
//define executor service to have 5 thread
1)
ExecutorService service=Executors.newFixedThreadPool(5);
2)
//replace move code insde while (command != 0) into a separate class that implements runnable, lets call this Task.
public class Task implements Runnable{
private final Integer command;
public Task(Integer command) {
this.command=command;
}
#Override
public void run() {
//do something, like switch statement
}
}
3) create a helper method, and call this method
public void process(Task t){
service.submit(t);
}

encode special character java

I'm trying to fix a bug in the code I wrote which convert a srt file to dxfp.xml. it works fine but when there is a special character such as an ampersand it throws an java.lang.NumberFormatException error. I tried to use the StringEscapeUtils function from apache commons to solve it. Can someone explain to me what it is I am missing here? thanks in advance!
public class SRT_TO_DFXP_Converter {
File input_file;
File output_file;
ArrayList<CaptionLine> node_list;
public SRT_TO_DFXP_Converter(File input_file, File output_file) {
this.input_file = input_file;
this.output_file = output_file;
this.node_list = new ArrayList<CaptionLine>();
}
class CaptionLine {
int line_num;
String begin_time;
String end_time;
ArrayList<String> content;
public CaptionLine(int line_num, String begin_time, String end_time,
ArrayList<String> content) {
this.line_num = line_num;
this.end_time = end_time;
this.begin_time = begin_time;
this.content = content;
}
public String toString() {
return (line_num + ": " + begin_time + " --> " + end_time + "\n" + content);
}
}
private void readSRT() {
BufferedReader bis = null;
FileReader fis = null;
String line = null;
CaptionLine node;
Integer line_num;
String[] time_split;
String begin_time;
String end_time;
try {
fis = new FileReader(input_file);
bis = new BufferedReader(fis);
do {
line = bis.readLine();
line_num = Integer.valueOf(line);
line = bis.readLine();
time_split = line.split(" --> ");
begin_time = time_split[0];
begin_time = begin_time.replace(',', '.');
end_time = time_split[1];
end_time.replace(',', '.');
ArrayList<String> content = new ArrayList<String>();
while (((line = bis.readLine()) != null)
&& (!(line.trim().equals("")))) {
content.add(StringEscapeUtils.escapeJava(line));
//if (StringUtils.isEmpty(line)) break;
}
node = new CaptionLine(line_num, begin_time, end_time, content);
node_list.add(node);
} while (line != null);
} catch (Exception e) {
System.out.println(e);
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String convertToXML() {
StringBuffer dfxp = new StringBuffer();
dfxp.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\">\n\t<head>\n\t\t<styling>\n\t\t\t<style id=\"1\" tts:backgroundColor=\"black\" tts:fontFamily=\"Arial\" tts:fontSize=\"14\" tts:color=\"white\" tts:textAlign=\"center\" tts:fontStyle=\"Plain\" />\n\t\t</styling>\n\t</head>\n\t<body>\n\t<div xml:lang=\"en\" style=\"default\">\n\t\t<div xml:lang=\"en\">\n");
for (int i = 0; i < node_list.size(); i++) {
dfxp.append("\t\t\t<p begin=\"" + node_list.get(i).begin_time + "\" ")
.append("end=\"" + node_list.get(i).end_time
+ "\" style=\"1\">");
for (int k = 0; k < node_list.get(i).content.size(); k++) {
dfxp.append("" + node_list.get(i).content.get(k));
}
dfxp.append("</p>\n");
}
dfxp.append("\t\t</div>\n\t</body>\n</tt>\n");
return dfxp.toString();
}
private void writeXML(String dfxp) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output_file));
out.write(dfxp);
out.close();
} catch (IOException e) {
System.out.println("Error Writing To File:"+ input_file +'\n');
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
if ((args.length < 2) || (args[1].equals("-h"))) {
System.out.println("\n<--- SRT to DFXP Converter Usage --->");
System.out
.println("Conversion: java -jar SRT_TO_DFXP.jar <input_file> <output_file> [-d]");
System.out
.println("Conversion REQUIRES a input file and output file");
System.out.println("[-d] Will Display XML Generated In Console");
System.out.println("Help: java -jar SRT_TO_DFXP.jar -h");
} else if (!(new File(args[0]).exists())) {
System.out.println("Error: Input SubScript File Does Not Exist\n");
} else {
SRT_TO_DFXP_Converter converter = new SRT_TO_DFXP_Converter(
new File(args[0]), new File(args[1]));
converter.readSRT();
String dfxp = converter.convertToXML();
if ((args.length == 3) && (args[2].equals("-d")))
System.out.println("\n" + dfxp + "\n");
converter.writeXML(dfxp);
System.out.println("Conversion Complete");
}
}
here's part of the srt file that it is throwing an error when exported and run as a jar file.
1
00:20:43,133 --> 00:20:50,599
literature and paper by Liversmith & Newman, and I think the point is well made that a host of factors

webserver is taking too long to respond in android

i have created a web server in android it works fine and it does not show any error and i have log saying server started on port 9000 but when i type the ip of my phone it says server is taking to long to connect.
Jhtts file: (the class which runs the server)
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.security.acl.Owner;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import dolphin.devlopers.com.R;
public class JHTTS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
try{
File documentRootDirectory = new File ("/sdcard/samer/");
JHTTP j = new JHTTP(documentRootDirectory,9000);
j.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JHTTP class:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;
public class JHTTP extends Thread {
private File documentRootDirectory;
private String indexFileName = "index.html";
private ServerSocket server;
private int numThreads = 50;
public JHTTP(File documentRootDirectory, int port,
String indexFileName) throws IOException {
if (!documentRootDirectory.isDirectory( )) {
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}
public JHTTP(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.html");
}
public JHTTP(File documentRootDirectory) throws IOException {
this(documentRootDirectory, 80, "index.html");
}
public void run( ) {
try {
Process process = Runtime.getRuntime().exec("su");
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(
new RequestProcessor(documentRootDirectory, indexFileName));
t.start( );
}
System.out.println("Accepting connections on port " + server.getLocalPort( ));
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept( );
request.setReuseAddress(true);
RequestProcessor.processRequest(request);
}
catch (IOException ex) {
}
}
}
public static void main(String[] args) {
// get the Document root
File docroot;
try {
docroot = new File("D:/");
}
catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Usage: java JHTTP docroot port indexfile");
return;
}
// set the port to listen on
try {
int port;
port = 9000;
JHTTP webserver = new JHTTP(docroot, port);
webserver.start( );
}
catch (IOException ex) {
System.out.println("Server could not start because of an "
+ ex.getClass( ));
System.out.println(ex);
}
}
}
Request Processor class :
package dolphin.developers.com;
import java.net.*;
import java.io.*;
import java.util.*;
public class RequestProcessor implements Runnable {
#SuppressWarnings("rawtypes")
private static List pool = new LinkedList( );
private File documentRootDirectory;
private String indexFileName = "index.html";
public RequestProcessor(File documentRootDirectory,
String indexFileName) {
if (documentRootDirectory.isFile( )) {
throw new IllegalArgumentException(
"documentRootDirectory must be a directory, not a file");
}
this.documentRootDirectory = documentRootDirectory;
try {
this.documentRootDirectory
= documentRootDirectory.getCanonicalFile( );
}
catch (IOException ex) {
}
if (indexFileName != null) this.indexFileName = indexFileName;
}
#SuppressWarnings("unchecked")
public static void processRequest(Socket request) {
synchronized (pool) {
pool.add(pool.size( ), request);
pool.notifyAll( );
}
}
public void run( ) {
// for security checks
String root = documentRootDirectory.getPath( );
while (true) {
Socket connection;
synchronized (pool) {
while (pool.isEmpty( )) {
try {
pool.wait( );
}
catch (InterruptedException ex) {
}
}
connection = (Socket) pool.remove(0);
}
try {
String filename;
String contentType;
OutputStream raw = new BufferedOutputStream(
connection.getOutputStream( )
);
Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(
new BufferedInputStream(
connection.getInputStream( )
),"ASCII"
);
StringBuffer requestLine = new StringBuffer( );
int c;
while (true) {
c = in.read( );
if (c == '\r' || c == '\n') break;
requestLine.append((char) c);
}
String get = requestLine.toString( );
// log the request
System.out.println(get);
StringTokenizer st = new StringTokenizer(get);
String method = st.nextToken( );
String version = "";
if (method.equals("GET")) {
filename = st.nextToken( );
if (filename.endsWith("/")) filename += indexFileName;
contentType = guessContentTypeFromName(filename);
if (st.hasMoreTokens( )) {
version = st.nextToken( );
}
File theFile = new File(documentRootDirectory,
filename.substring(1,filename.length( )));
if (theFile.canRead( )
// Don't let clients outside the document root
&& theFile.getCanonicalPath( ).startsWith(root)) {
DataInputStream fis = new DataInputStream(
new BufferedInputStream(
new FileInputStream(theFile)
)
);
byte[] theData = new byte[(int) theFile.length( )];
fis.readFully(theData);
fis.close( );
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 200 OK\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-length: " + theData.length + "\r\n");
out.write("Content-type: " + contentType + "\r\n\r\n");
out.flush( );
} // end if
// send the file; it may be an image or other binary data
// so use the underlying output stream
// instead of the writer
raw.write(theData);
raw.flush( );
} // end if
else { // can't find the file
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 404 File Not Found\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>File Not Found</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 404: File Not Found</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
else { // method does not equal "GET"
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 501 Not Implemented\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP 1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>Not Implemented</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 501: Not Implemented</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
catch (IOException ex) {
}
finally {
try {
connection.close( );
}
catch (IOException ex) {}
}
} // end while
} // end run
public static String guessContentTypeFromName(String name) {
if (name.endsWith(".html") || name.endsWith(".htm")) {
return "text/html";
}
else if (name.endsWith(".txt") || name.endsWith(".java")) {
return "text/plain";
}
else if (name.endsWith(".gif")) {
return "image/gif";
}
else if (name.endsWith(".class")) {
return "application/octet-stream";
}
else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) {
return "image/jpeg";
}
else if (name.endsWith(".png") ) {
return "image/png";
}
else if (name.endsWith(".js")) {
return "text/javascript";
}
else if (name.endsWith(".js")) {
return "text/javascript";
}
else if (name.endsWith(".css")) {
return "text/css";
}
else return "text/plain";
}
} // end RequestProcessor
Logcat window:
Accepting connections on port 9000
Document Root: D:\
now when i connect to my web server in my log i get
Logcat Update:
07-29 14:42:46.175: D/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
07-29 14:47:46.195: D/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
The log says it's accepting connections on port 80, but your server runs on port 9000 - I guess that's the problem.

Categories