I currently have a java backend running on my server and I have come across a script to communicate from Java to Node.js. I am wondering how I can modify the script to allow more then one message at a time, and if possible, use it in reverse to communicate back to Java.
Here is the code:
Java Side:
package com.timetablr.backend.nodecommunicator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class NodeCommunicator {
public static void main(String[] args) {
try {
Socket nodejs = new Socket("localhost", 8080);
sendMessage(nodejs, "testnamespace");
Thread.sleep(100);
int x = 0;
while (true)
{
sendMessage(nodejs, x + "");
x++;
Thread.sleep(1000);
System.out.println(x + " has been sent to server");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException {
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}
public static String readMessage(Socket s) throws IOException {
InputStream is = s.getInputStream();
int curr = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((curr = is.read()) != -1) {
if (curr == '\n') {
break;
}
baos.write(curr);
}
return baos.toString("UTF-8");
}
}
Node.js Side:
var javaPort = 8080;
var sIOPort = 8081;
var javaServer = require('net').createServer();
var browserServer = require('socket.io').listen(sIOPort);
console.log('=====================================================');
console.log('JamesS237 Timetablr Node.js/Java Communication Module');
console.log('=====================================================');
console.log('Socket.IO version: ' + require('socket.io').version);
javaServer.on('listening', function () {
console.log('Server is listening on ' + javaPort);
});
javaServer.on('error', function (e) {
console.log('Server error: ' + e.code);
});
javaServer.on('close', function () {
console.log('Server closed');
});
javaServer.on('connection', function (javaSocket) {
var clientAddress = javaSocket.address().address + ':' + javaSocket.address().port;
console.log('Java ' + clientAddress + ' connected');
var firstDataListenner = function (data) {
console.log('Received namespace from java: ' + data);
console.log(data);
javaSocket.removeListener('data', firstDataListenner);
createNamespace(data, javaSocket);
}
javaSocket.on('data', firstDataListenner);
javaSocket.on('close', function() {
console.log('Java ' + clientAddress + ' disconnected');
});
});
javaServer.listen(javaPort);
function createNamespace(namespaceName, javaSocket) {
var browserConnectionListenner = function (browserSocket) {
console.log('Browser Connected');
var javaSocketDataListenner = function(data) {
console.log('Data received from java socket and sent to browser: ' + data);
browserSocket.emit('m', data + '\r\n');
}
var javaSocketClosedListenner = function() {
console.log('The java socket that was providing data has been closed, removing namespace');
browserSocket.disconnect();
browserServer.of('/' + namespaceName).removeListener('connection', browserConnectionListenner);
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
}
javaSocket.on('close', javaSocketClosedListenner);
javaSocket.on('data', javaSocketDataListenner);
browserSocket.on('disconnect', function () {
console.log('Browser Disconnected');
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
});
}
var namespace = browserServer.of('/' + namespaceName).on('connection', browserConnectionListenner);
}
Thanks in advance, this is a tricky one
Related
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.
Here's my code I get the js ws working but when y try to send a message to the websocket :glassfish returns:
INFO: Error : SessionImpl{uri=/Formosa2/endpoint, id='b821d249-6435-45fe-812d- 577bc5fc8fca', endpoint=EndpointWrapper{endpointClass=null, endpoint=org.glassfish.tyrus.core.AnnotatedEndpoint#1602760, uri='/Formosa2/endpoint', contextPath='/Formosa2'}}
#ServerEndpoint(value = "/endpoint")
#Singleton
public class websocket {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
#OnMessage
public void onMessage(String message) {
String filteredMessage = String.format("%s: %s", message.toString());
broadcast(filteredMessage);
System.out.println(message);
}
#OnOpen
public void onOpen(Session peer){
peers.add(peer);
String message = String.format("* %s %s", "User has joined.");
broadcast(message);
}
#OnClose
public void onClose(Session peer){
peers.remove(peer);
}
#OnError
public void onError(Session aclientSession, Throwable aThrowable) {
System.out.println("Error : " + aclientSession);
}
private void broadcast(String message) {
for (Session peer : peers) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
peer.getBasicRemote().sendText(buffer.toString());
} catch (IOException ignore) {
// Ignore
}
}
}
}
and
<script type="text/javascript">
ws = new WebSocket('ws://' + window.location.host + '/Formosa2/endpoint'); //Annotation
ws.onopen = function(event) {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
sendMessage();
}
};
};
ws.onmessage = function(event) {
sendMessage(event);
};
ws.onclose = function(event) {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
ws.onerror = function(event){
alert("Error : " + event.data);
Console.log(message.data);
};
function sendMessage (event) {
var text = document.getElementById('form:texto').value;
var select = document.getElementById('form:empresaidEmpresa');
var text2 = document.getElementById('inicio_input').value;
var name = select.options[select.selectedIndex].text;
ws.send(texto +', '+ name +',' + text2);
document.getElementById('chat').value = '';
}
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
// Chat.initialize();
</script>
String message = String.format("* %s %s", "User has joined.");
this line was the problem
format modifiers were incorret,I was able to discover that by reading in the log (system.out..) of the aThrowable parameter.
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.
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');
FYI This is homework. I have to build a Java Chat server. I have been able to build a server which communicates with 1 client. But I need this to communicate with multiple users.
A user is supposed to type in the person's name they wish to talk to followed by a dash (-) and then the message to be sent. I am able to get users signed on but I am not able to get the list of users to print out or the messages to send to other users. Here is the server code:
/**
Threaded Server
*/
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;
public class ThreadedServer
{
public static void main( String[] args) throws Exception
{
HashMap<String, Socket> users = new HashMap<String, Socket>( );
ServerSocket server = new ServerSocket(5679);
System.out.println( "THE CHAT SERVER HAS STARTED! =)" );
while(true)
{
Socket client = server.accept();
ThreadedServer ser = new ThreadedServer();
ClientFromThread cft =ser.new ClientFromThread(client);
String name = cft.getUserName();
users.put( name, client );
cft.giveUsersMap( users );
//cft.giveOnlineUsers( ); //DOES NOT WORK YET!!!!
System.out.println("Threaded server connected to "
+ client.getInetAddress() + " USER: " + name );
}
}
//***************************************************************************************************
class ClientFromThread extends Thread
{
private Socket client;
private Scanner fromClient;
private PrintWriter toClient;
private String userName;
HashMap<String, Socket> users;
public ClientFromThread( Socket c ) throws Exception
{
client = c;
fromClient = new Scanner( client.getInputStream() );
toClient = new PrintWriter( client.getOutputStream(), true );
userName = getUser();
start();
}
public void giveUsersMap( HashMap<String, Socket> users )
{
this.users = users;
}
//THIS DOESNT WORK YET... IT PRINTS THE FIRST LINE BUT NOT THE LIST
public void giveOnlineUsers()
{
toClient.println("These users are currently online:");
Set<String> userList = users.keySet();
String[] userNames = null;
userList.toArray( userNames );
for( int i = 0; i< userNames.length; i++ )
{
toClient.println(userNames[i]);
}
}
public String getUserName()
{
return userName;
}
private String getUser()
{
String s = "";
while( (s.length() < 1) || (s == null) )
{
toClient.println("What is your first name? ");
s=fromClient.nextLine().trim();
}
toClient.println("Thank You! Welcome to the chat room " + s + ".");
return s.toUpperCase();
}
public void run()
{
String s = null;
String toUser;
String mesg;
while( (s=fromClient.nextLine().trim()) != null )
{
if( s.equalsIgnoreCase( "END" )) break;
for( int i=0; i<s.length(); i++)
{
if( s.charAt(i) == '-' )
{
toUser = s.substring( 0, i ).trim().toUpperCase();
mesg = s.substring( i+1 ).trim();
Socket client = users.get( toUser );
try
{
ClientToThread ctt = new ClientToThread(client);
ctt.sendMesg( mesg, toUser );
ctt.start();
}
catch(Exception e){e.printStackTrace();}
break;
}
if( (i+1) == s.length() )
{
toClient.println("Sorry the text was invalid. Please enter a user name " +
"followed by a dash (-) then your message.");
}
}
}
try
{
fromClient.close();
toClient.close();
client.close();
}
catch(Exception e){e.printStackTrace();}
}
} //end class ClientFromThread
//***************************************************************************************************
class ClientToThread extends Thread
{
private Socket client;
private PrintWriter toClient;
private String mesg;
public ClientToThread( Socket c ) throws Exception
{
client = c;
toClient = new PrintWriter( client.getOutputStream(), true );
}
public void sendMesg( String mesg, String userName )
{
this.mesg = userName + ": " + mesg;
}
public void run()
{
toClient.println(mesg);
try
{
toClient.close();
client.close();
}
catch(Exception e){e.printStackTrace();}
}
} //end class ClientToThread
//***************************************************************************************************
} //end class ThreadedServer
Here is the Client code"
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class ReverseClient
{
public static void main( String[] args ) throws Exception
{
String line = null;
Socket server= new Socket( "10.0.2.103", 5679);
System.out.println( "Connected to host: " + server.getInetAddress() );
BufferedReader fromServer = new BufferedReader(
new InputStreamReader(server.getInputStream()) );
PrintWriter toServer = new PrintWriter( server.getOutputStream(), true );
BufferedReader input = new BufferedReader(
new InputStreamReader(System.in) );
while( (line=input.readLine()) !=null )
{
toServer.println(line);
System.out.println( fromServer.readLine() );
}
fromServer.close();
toServer.close();
input.close();
server.close();
}
}
Here is the console output (the top is the server, bottom is the client):
I am getting errors (as shown in the image above) and the messages are not sending. Any suggestions on how to take care of these issues?
So far I found this to be a problem, but I don't think this is the only problem..
This will help the NoSuchElementException
On around line 90 Change this...
while( (s=fromClient.nextLine().trim()) != null )
{
to this...
while(fromClient.hasNext())
{
s = fromClient.nextLine().trim();
OK just found another problem in ClientToThread.run()... You are closing the client connections after you send the first message. I commented them both out and it seems to be working a little better.
public void run()
{
toClient.println(mesg);
try {
//toClient.close();
//client.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Your first problem is with the parsing of the message from the user.
You loop through the string, and it has one of two options, either the character is a dash or it is invalid.
So, ideally, you should be getting an invalid message for the number of a characters in the username before the dash.
You should use String.indexOf to determine where the dash is, and then split the message into it's two parts, and if the result of indexOf is -1 then it is an invalid message.