Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have an server/client application that sends/receives updates about the users of the app (Members). Unfortunately, when the client on the Android device sends any getUpdate/sendUpdate Objects the server receives them as null.
I also have a PC version of the Android client that works perfectly fine. It has the same methods and everything.
Here is the client on the Android device:
public class AndroidApplication extends Application{
public static Log log;
private final static String TAG = "AndroidApplication";
public static final String SERVER = "192.168.1.136";
public static boolean chatCreated = false;
public static String chatText;
public static String username, level = MemberMessage.LEVEL4;
public static Context context;
public static int points = 0;
public static UpdateMember k;
#Override
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static void updateMember(){
k = new UpdateMember(UpdateMember.SEND);
k.start();
}
public static void getUpdateMember(){
k = new UpdateMember(UpdateMember.GET);
k.start();
}
public static void stopUpdateMember(){
AndroidApplication.k = null;
}
static class UpdateMember extends Thread{
static final int GET=0,SEND=1;
boolean didConnectWork;
boolean didUpdateWork;
boolean didDisconnectWork;
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
boolean GetSend;
public UpdateMember(int get_send){
switch(get_send){
case UpdateMember.GET:
GetSend = true;
break;
case UpdateMember.SEND:
GetSend = false;
break;
}
}
public void run(){
if(GetSend){
didConnectWork = connect();
didUpdateWork = getUpdate();
getInfoFromServer();
didDisconnectWork = disconnect();
}else{
didConnectWork = connect();
didUpdateWork = sendUpdate();
try{
getInfoFromServer();
}catch(Exception e){
Log.i(TAG, "Something Bad");
}
didDisconnectWork = disconnect();
}
AndroidApplication.stopUpdateMember();
}
private boolean connect() {
try{
socket = new Socket(SERVER, 1520);
}catch(Exception e){
Log.i(TAG, "Couldn't connect to Member Server");
Log.i(TAG, e.getMessage());
return false;
}
Log.i(TAG, "Connection Accepted at Membe Server!");
/*
* Create both data streams
*/
try{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}catch(IOException e){
Log.i(TAG, "Couldn't connect to Member Server");
return false;
}
try{
sOutput.writeObject(username);
}catch(IOException e){
Log.i(TAG, "Couldn't send username.");
return false;
}
//everything worked
Log.i(TAG, "Connected to Member Server.");
return true;
}
private boolean sendUpdate() {
MemberMessage mh = new MemberMessage(MemberMessage.UPDATE, AndroidApplication.username,
AndroidApplication.points, AndroidApplication.level);
try{
sOutput.writeObject(mh);
}catch(IOException e){
Log.i(TAG, "Couldn't update info");
return false;
}
//everything worked!
Log.i(TAG, Integer.toString(mh.getType()));
Log.i(TAG, "Update sent!");
return true;
}
private boolean getUpdate(){
try{
sOutput.writeObject(new MemberMessage(MemberMessage.UPDATE_REQUEST,
AndroidApplication.username, -1, null));
}catch(IOException e){
Log.i(TAG, "Couldn't send GET message info");
return false;
}
//itworked
Log.i(TAG, "GET Update sent!");
return true;
}
private void getInfoFromServer(){
MemberMessage MM;
/*
* Will listen for both an update message and a Diconnect messafge form the
* server.
*/
boolean keep = true;
while(keep){
//************************************
try{
MM = (MemberMessage) sInput.readObject();
}catch(IOException e){
Log.i(TAG, "Couldn't read message from server.");
break;
} catch (ClassNotFoundException e) {
Log.i(TAG, "Couldn't update info");
break;
}
//the message to stop listening for updates
switch(MM.getType()){
case MemberMessage.DISCONECT:
Log.i(TAG, "Received dsconnect message.");
keep = false;
break;
case MemberMessage.UPDATE:
/*
* Update our info in turn
*/
AndroidApplication.points = MM.getNumPoints();
AndroidApplication.level = MM.getLevel();
Log.i(TAG, "Updatted member with Points = " + AndroidApplication.points
+ " and Level = " + AndroidApplication.level);
try{
//tell the sever we recieved the info
sOutput.writeObject(new MemberMessage(MemberMessage.RECIEVED, null, -1, null));
}catch(IOException e){
Log.i(TAG, "Couldn't send received message");
keep = false;
}
break;
}
//*****************************************
}
}
private boolean disconnect() {
try{
sOutput.writeObject(new MemberMessage(MemberMessage.DISCONECT, null, -1, null));
}catch(IOException e){
Log.i(TAG, "Couldn't disconnet");
}
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {
Log.i(TAG, "Couldn't close output");
return false;
}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {
Log.i(TAG, "Couldn't close input");
return false;
}
try {
if(socket != null) socket.close();
}
catch (Exception e) {
Log.i(TAG, "Couldn't close socket");
return false;
}
return true;
}
}
}
For the PC version:
public class UpdateTest {
public static final String SERVER = "192.168.1.136";
public static boolean chatCreated = false;
public static String chatText;
public static String username = "TESTER", level = MemberMessage.LEVEL1;
public static int points = 90;
public static UpdateMember k;
public static void updateMember(){
k = new UpdateMember(UpdateMember.SEND);
k.start();
}
public static void getUpdateMember(){
k = new UpdateMember(UpdateMember.GET);
k.start();
}
public static void stopUpdateMember(){
UpdateTest.k = null;
}
static class UpdateMember extends Thread{
static final int GET=0,SEND=1;
boolean didConnectWork;
boolean didUpdateWork;
boolean didDisconnectWork;
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
boolean GetSend;
public UpdateMember(int get_send){
switch(get_send){
case UpdateMember.GET:
GetSend = true;
break;
case UpdateMember.SEND:
GetSend = false;
break;
}
}
public void run(){
if(GetSend){
didConnectWork = connect();
didUpdateWork = getUpdate();
getInfoFromServer();
didDisconnectWork = disconnect();
}else{
didConnectWork = connect();
didUpdateWork = sendUpdate();
getInfoFromServer();
didDisconnectWork = disconnect();
}
UpdateTest.stopUpdateMember();
}
private boolean connect() {
try{
socket = new Socket(SERVER, 1520);
}catch(Exception e){
return false;
}
/*
* Create both data streams
*/
try{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}catch(IOException e){
return false;
}
try{
sOutput.writeObject(username);
}catch(IOException e){
return false;
}
//everything worked
return true;
}
private boolean sendUpdate() {
try{
sOutput.writeObject(new MemberMessage(MemberMessage.UPDATE, UpdateTest.username,
UpdateTest.points, UpdateTest.level));
}catch(IOException e){
return false;
}
//everything worked!
return true;
}
private boolean getUpdate(){
try{
sOutput.writeObject(new MemberMessage(MemberMessage.UPDATE_REQUEST,
UpdateTest.username, -1, null));
}catch(IOException e){
return false;
}
//itworked
return true;
}
private void getInfoFromServer(){
MemberMessage MM;
/*
* Will listen for both an update message and a Diconnect messafge form the
* server.
*/
boolean keep = true;
while(keep){
//************************************
try{
MM = (MemberMessage) sInput.readObject();
}catch(IOException e){
break;
} catch (ClassNotFoundException e) {
break;
}
//the message to stop listening for updates
switch(MM.getType()){
case MemberMessage.DISCONECT:
keep = false;
break;
case MemberMessage.UPDATE:
/*
* Update our info in turn
*/
UpdateTest.points = MM.getNumPoints();
UpdateTest.level = MM.getLevel();
try{
//tell the sever we received the info
sOutput.writeObject(new MemberMessage(MemberMessage.RECIEVED, null, -1, null));
}catch(IOException e){
keep = false;
}
break;
}
//*****************************************
}
}
private boolean disconnect() {
System.out.println("Disconectin...");
System.out.println(UpdateTest.username);
System.out.println(UpdateTest.points);
System.out.println(UpdateTest.level);
try{
sOutput.writeObject(new MemberMessage(MemberMessage.DISCONECT, null, -1, null));
}catch(IOException e){
}
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {
return false;
}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {
return false;
}
try {
if(socket != null) socket.close();
}
catch (Exception e) {
return false;
}
return true;
}
}
public static void main(String... args){
updateMember();
getUpdateMember();
}
}
And now for the server:
public class MemberServer {
// a unique ID for each connection
private static int uniqueId;
//ArrayList of connected members
private static ArrayList<Member> ml;
//Arraylist of the Created user profiles
private static ArrayList<String> members = new ArrayList<String>();
//the port to be run on
static private final int PORT = 1520;
//will keep the server running
static private boolean keepGoing;
public MemberServer(){
ml = new ArrayList<Member>();
readUserList();
}
private void readUserList() {
BufferedReader in = null;
try{
in = new BufferedReader(new FileReader("/home/steven/Documents/Android/MemberServerTest/Users.txt"));
String str = in.readLine();
while((str = in.readLine()) != null){
members.addAll(Arrays.asList(str.split(",")));
}
}catch(IOException e){
e.printStackTrace();
}
}
public void begin(){
keepGoing = true;
/*
* Create a socket server and wait for connections
*/
try{
ServerSocket serverSocket = new ServerSocket(1520);
//loop to wait for connections
while(keepGoing){
//message to say that we are waiting
display("Server is waiting for Members on port " + PORT + ".");
Socket socket = serverSocket.accept();// acctep connection
//if asked to stop
if(!keepGoing){
break;
}
Member m = new Member(socket);
ml.add(m);
m.start();
}
try{
serverSocket.close();
for(int i = 0; i < ml.size(); ++i){
Member mb = ml.get(i);
try{
mb.sInput.close();
mb.sOutput.close();
mb.socket.close();
mb.createUserData(mb.username);
}catch(IOException ioE){}
}
}catch(Exception e){}
Writer o = null;
o = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("/home/steven/Documents/Android/MemberServerTest/Users.txt" ), "utf-8"));
o.write("\n");
for(Member k:ml){
o.write(k.username + ",");
}
o.close();
}catch(IOException e){
e.printStackTrace();
}
}
protected static void stop(){
System.out.println("Now Stoping Server...");
keepGoing = false;
try{
new Socket("localhost", PORT);
}catch(Exception e){}
}
private void display(String string) {
System.out.println(string);
}
synchronized static void remove(int id){
for(Member mn: ml){
if(mn.id == id){
ml.remove(mn);
return;
}
}
}
public static void main(String... args){
MemberServer ms = new MemberServer();
ms.begin();
}
class Member extends Thread{
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
public ArrayList<String> properties = new ArrayList<String>();
public int id;
public String username,level = MemberMessage.LEVEL4;
public int numPoints = 0, numUpvotes = 0;
public MemberMessage memMes;
Member(Socket socket){
boolean exists = false;
id = ++uniqueId;
this.socket = socket;
System.out.println("Thread trying to create Object Input/Output Streams");
try{
//create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
//read the username
username = (String) sInput.readObject();
}catch(IOException e){} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for(String str:members){
if(str.equals(username)){
loadUserData();
exists = true;
}
}
if(!exists){
createUserData(username);
}
}
private void createUserData(String username) {
Writer out = null;
try{
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("/home/steven/Documents/Android/MemberServerTest/" + username + ".txt" ), "utf-8"));
out.write("\nUsername:" + username + ";Points:" + numPoints + ";Level:" + level + ";");
System.out.println("Member data wittem for " + username);
}catch(IOException e){}
finally{
try{
out.close();
}catch(Exception e){}
}
}
private void loadUserData() {
BufferedReader in = null;
try{
in = new BufferedReader(new FileReader("/home/steven/Documents/Android/MemberSeverTest/" + username +".txt"));
String str;
str = in.readLine();
while(( str = in.readLine()) != null){
properties.addAll(Arrays.asList(str.split(";")));
}
in.close();
}catch(IOException e){}
finally{
try{
in.close();
}catch(Exception e){}
}
for(String i:properties){
String[] me = i.split(":");
if(me[0].equals("Username")){
username = me[1];
}else if(me[0].equals("Points")){
numPoints = Integer.parseInt(me[1]);
}else if(me[0].equals("Level")){
level = me[1];
}
}
System.out.println("Member data loaded for " + username);
}
public void run(){
boolean keepGoing = true;
while(keepGoing){
try{
memMes = (MemberMessage) sInput.readObject();
if(memMes != null){
memMes = new MemberMessage(MemberMessage.UPDATE, this.username, this.numPoints, this.level);
}else{
switch(memMes.getType()){
case MemberMessage.UPDATE:
System.out.println("Update message received from " + username);
this.username = memMes.getUsername();
this.numPoints = memMes.getNumPoints();
this.level = memMes.getLevel();
writeToMember(new MemberMessage(MemberMessage.UPDATE, this.username, this.numPoints, this.level));
break;
case MemberMessage.RECIEVED:
System.out.println("Received message recieved from " + username);
writeToMember(new MemberMessage(MemberMessage.DISCONECT, null, -1, null));
break;
case MemberMessage.DISCONECT:
System.out.println("Disconnecting from " + username + "...");
keepGoing = false;
break;
case MemberMessage.UPDATE_REQUEST:
display("GET request from " + username);
writeToMember(new MemberMessage(MemberMessage.UPDATE, this.username, this.numPoints, this.level));
break;
case 100:
System.out.println(memMes.getLevel());
MemberServer.stop();
break;
}
}
}catch(IOException e){keepGoing = false; display("IOException");}
catch (ClassNotFoundException e){keepGoing = false;}
catch(NullPointerException e){
keepGoing = false;
display("NullPointerException");
}catch(Exception e){
e.printStackTrace();
}
}
remove(id);
close();
}
private void writeToMember(MemberMessage j){
try{
sOutput.writeObject(j);
}catch(IOException e){
System.out.println("Error writing to " + username);
e.printStackTrace();
}
}
// try to close everything
private void close() {
createUserData(username);
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}
}
}
Now, the issue I see is when the actual sendUpdate() method where the sOutput.wirteObject(mh) is called. At the server side this sent object is received as null. The way the server connects is that it accepts a socket connection, creates a Member Object to handle the IO, and then listens for any incomming MemberMessage Objects. The problem occurs when it receives the MemberMessage; however, its value is null.
Any ideas??
Thanks for any help beforehand!
Also, here is the MemberMessage class:
/**
* This class will define the updates to the different properties of a Member object.
* Properties include: usename, #points, and level.
*
*
*/
public class MemberMessage implements Serializable{
protected static final long serialVersionUID = 110L;
public static final int UPDATE = 0, DISCONECT = 1, RECIEVED = 2, UPDATE_REQUEST = 3;
public static final String LEVEL1 = "I'm an expert and I want to help"
,LEVEL2 = "I'm doind okay and I don't need help - but I'm not confident enough to help others."
,LEVEL3 = "I need help"
,LEVEL4 = "I need a tutor because I just can't get the hang of this subject.";
private String username, level;
private int numPoints;
private int type;
public MemberMessage(int type, String username, int numPoints, String level){
this.type = type;
this.username = username;
this.numPoints = numPoints;
this.level = level;
}
public String getUsername(){
return this.username;
}
public int getNumPoints(){
return this.numPoints;
}
public String getLevel(){
return this.level;
}
public int getType(){
return this.type;
}
}
Your subsequent edit has obscured the fact, and indeed made your post entirely pointless, but you got an IOException calling readObject() and then continued as though you didn't get it, so the variable you read into was still null. Don't write code like this. The code that depends on the readObject() call succeeding should have been inside the try block along with the call.
And when you get an IOException, especially an EOFException, you should close the socket and exit the reading loop. Immediately. Not as at present.
Related
UPDATED
There is my updated code after the response,
I have one problem, now, i didn't receive anything :
Problem :
Connexion cliente reçue.
Lancement du traitement de la connexion cliente
Exception in thread "Thread-1" java.lang.NullPointerException
at cuisine.TimeServer.onResponseReceived(TimeServer.java:85)
at cuisine.ClientProcessor.run(ClientProcessor.java:43)
at java.base/java.lang.Thread.run(Thread.java:844)
TimeServer: 85 : Callback
#Override
public void onResponseReceived(String response) {
// When the response is received from ClientProcessor
// this method is called (by ClientProcessor).
// Your response is the parameter String response.
callback.onResponse(response);
}
Client processor: 43 :
server.onResponseReceived(response);
One client can connect but i can't receive anything : Json or text.
There is my new Java Code :
Main.java :
import cuisine.TimeServer.OnResponseReceivedListener;
public class main implements OnResponseReceivedListener {
public static void main(String[] args) throws IOException {
String host = "192.168.1.21";
int port = 8080;
TimeServer ts = new TimeServer(host, port);
ts.open();
System.out.println("------------Connected ! ------------");
}
#Override
public void onResponse(String response) {
doSomethingWith(response);
System.out.println("REPONSE : ");
System.out.println(response);
}
private void doSomethingWith(String response) {
System.out.println("REPONSE : ");
System.out.println(response);
}
}
I don't really know how to use the response now, because the sysout "RESPONSE" is not in my console
TimeServer.java :
...
import cuisine.ClientProcessor.Server;
public class TimeServer implements Server {
public interface OnResponseReceivedListener {
void onResponse(String response);
}
private int port = 2345;
private String host = "127.0.0.1";
private ServerSocket server = null;
private boolean isRunning = true;
private OnResponseReceivedListener callback;
public TimeServer() {
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TimeServer(String pHost, int pPort) {
host = pHost;
port = pPort;
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void open() {
Thread t =
new Thread(
new Runnable() {
public void run() {
while (isRunning == true) {
try {
Socket client = server.accept();
System.out.println("Connexion cliente reçue.");
ClientProcessor c = new ClientProcessor(client);
Thread t = new Thread(c);
// Don't forget to define the Server for ClientProcessor
c.addServer(TimeServer.this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
server = null;
}
}
});
t.start();
}
#Override
public void onResponseReceived(String response) {
// When the response is received from ClientProcessor
// this method is called (by ClientProcessor).
// Your response is the parameter String response.
callback.onResponse(response);
}
public void addOnResponseReceivedListener(OnResponseReceivedListener listener) {
callback = listener;
}
public void removeOnResponseReceivedListener() {
callback = null;
}
public void close() {
isRunning = false;
}
}
ClientProcessor.java :
public class ClientProcessor implements Runnable {
public interface Server {
void onResponseReceived(String response);
}
private Socket sock;
private PrintWriter writer = null;
private BufferedInputStream reader = null;
public List<Dish> dish;
// Your server instance
private Server server;
public ClientProcessor(Socket pSock) {
this.sock = pSock;
}
public void run() {
System.err.println("Lancement du traitement de la connexion cliente");
boolean closeConnexion = false;
while (!sock.isClosed()) {
try {
writer = new PrintWriter(sock.getOutputStream());
reader = new BufferedInputStream(sock.getInputStream());
String response = read();
// report the response to TimeServer
server.onResponseReceived(response);
InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress();
String debug = "";
debug = "Thread : " + Thread.currentThread().getName() + ". ";
debug += "Demande de l'adresse : " + remote.getAddress().getHostAddress() + ".";
debug += " Sur le port : " + remote.getPort() + ".\n";
debug += "\t -> Commande reçue : " + response + "\n";
System.err.println("\n" + debug);
String toSend = "";
switch (response.toUpperCase()) {
case "ORDER":
toSend = "Dish";
break;
case "CLOSE":
toSend = "Communication terminée";
closeConnexion = true;
break;
default:
toSend = "Commande inconnu !";
break;
}
writer.write(toSend);
writer.flush();
if (closeConnexion) {
System.err.println("COMMANDE CLOSE DETECTEE ! ");
writer = null;
reader = null;
sock.close();
break;
}
} catch (SocketException e) {
System.err.println("LA CONNEXION A ETE INTERROMPUE ! ");
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addServer(Server server) {
this.server = server;
}
private void removeServer() {
server = null;
}
// La méthode que nous utilisons pour lire les réponses
private String read() throws IOException {
String response = "";
int stream;
byte[] b = new byte[4096];
stream = reader.read(b);
response = new String(b, 0, stream);
return response;
}
}
Thanks,
Benjamin.
Update (updated Main.java)
Update No2 (Removed static methods from Main.java and use a Main object)
Edit: (removed previous answer about sockets)
This is the json response, now i want to use it in my main : on
another class in the same package.
Since you've stated that you are getting a response from client but you don't know how to manipulate it in your Main class then your issue is not about sockets.
A solution: Use callbacks:
ClientProcessor will report the response to TimeServer.
TimeServer will report that response to Main.
Make ClientProcessor aware of the server and report when the response is fetched.
public class ClientProcessor implements Runnable {
public interface Server {
void onResponseReceived(String response);
}
private Socket sock;
private PrintWriter writer = null;
private BufferedInputStream reader = null;
public List<Dish> dish;
// Your server instance
private Server server;
public ClientProcessor(Socket pSock) {
this.sock = pSock;
}
public void run() {
System.err.println("Lancement du traitement de la connexion cliente");
boolean closeConnexion = false;
while (!sock.isClosed()) {
try {
writer = new PrintWriter(sock.getOutputStream());
reader = new BufferedInputStream(sock.getInputStream());
String response = read();
// report the response to TimeServer
server.onResponseReceived(response);
InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress();
String debug = "";
debug = "Thread : " + Thread.currentThread().getName() + ". ";
debug += "Demande de l'adresse : " + remote.getAddress().getHostAddress() + ".";
debug += " Sur le port : " + remote.getPort() + ".\n";
debug += "\t -> Commande reçue : " + response + "\n";
System.err.println("\n" + debug);
String toSend = "";
switch (response.toUpperCase()) {
case "ORDER":
toSend = "Dish";
break;
case "CLOSE":
toSend = "Communication terminée";
closeConnexion = true;
break;
default:
toSend = "Commande inconnu !";
break;
}
writer.write(toSend);
writer.flush();
if (closeConnexion) {
System.err.println("COMMANDE CLOSE DETECTEE ! ");
writer = null;
reader = null;
sock.close();
break;
}
} catch (SocketException e) {
System.err.println("LA CONNEXION A ETE INTERROMPUE ! ");
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addServer(Server server) {
this.server = server;
}
private void removeServer() {
server = null;
}
// La méthode que nous utilisons pour lire les réponses
private String read() throws IOException {
String response = "";
int stream;
byte[] b = new byte[4096];
stream = reader.read(b);
response = new String(b, 0, stream);
return response;
}
}
Now go to TimeServer and make it aware of Main (same procedure as before). You must also need to report the response to Main when its being received from ClientProcessor.
public class TimeServer implements Server {
public interface OnResponseReceivedListener {
void onResponse(String response);
}
private int port = 2345;
private String host = "127.0.0.1";
private ServerSocket server = null;
private boolean isRunning = true;
private OnResponseReceivedListener callback;
public TimeServer() {
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TimeServer(String pHost, int pPort) {
host = pHost;
port = pPort;
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void open() {
Thread t =
new Thread(
new Runnable() {
public void run() {
while (isRunning == true) {
try {
Socket client = server.accept();
System.out.println("Connexion cliente reçue.");
Thread t = new Thread(new ClientProcessor(client));
// Don't forget to define the Server for ClientProcessor
t.addServer(TimeServer.this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
server = null;
}
}
});
t.start();
}
#Override
public void onResponseReceived(String response) {
// When the response is received from ClientProcessor
// this method is called (by ClientProcessor).
// Your response is the parameter String response.
callback.onResponse(response);
}
public void addOnResponseReceivedListener(OnResponseReceivedListener listener) {
callback = listener;
}
public void removeOnResponseReceivedListener() {
callback = null;
}
public void close() {
isRunning = false;
}
}
Finaly, make your Main to listen to TimeServer and do something when it receives the response.
public class Main implements OnResponseReceivedListener {
public static void main(String[] args) {
Main application = new Main();
TimeServer ts = application.createTimeServer();
ts.addOnResponseReceivedListener(application);
ts.open();
System.out.println("------------Connected ! ------------");
}
#Override
public void onResponse(String response) {
doSomethingWith(response);
}
private void doSomethingWith(String response) {
// Your logic for the response here...
}
private TimeServer createTimeServer() {
String host = "192.168.43.178";
int port = 8080;
return new TimeServer(host, port);
}
}
This is the SocketServer code that generates a server thread
public class ProcessorCorresponder {
protected final static Logger logger = LogManager.getLogger( ProcessorCorresponder.class );
private static int port = Integer.parseInt(PropertiesLoader.getProperty("appserver.port") == null ? "666" : PropertiesLoader.getProperty("appserver.port"));
private static int maxConnections = Integer.parseInt(PropertiesLoader.getProperty("appserver.maxconnections") == null ? "666" : PropertiesLoader.getProperty("appserver.maxconnections"));
public static void main(String[] args) {
logger.info("Starting server .. "
+ "[port->" + port
+ ",databaseName->" + databaseName + "]");
try (ServerSocket listener = new ServerSocket();) {
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(port));
Socket server;
int i = 0;
while((i++ < maxConnections) || (maxConnections == 0)) {
server = listener.accept();
logger.debug(
"New Thread listening on " + server.getLocalAddress().toString() + ":" + server.getLocalPort()
+ ", initiated from IP => " + server.getInetAddress().toString() + ":" + server.getPort()
);
MySocketServer socSrv = new MySocketServer (server);
Thread t = new Thread( socSrv );
t.start();
}
} catch (Exception ex) {
logger.error("Error in ProcessorInterface", ex);
}
}
}
Server code: This is a thread to handle one connection, there is a program that monitors a serversocket and spins off request threads as needed.
public class MySocketServer implements Runnable {
protected final static Logger logger = LogManager.getLogger(MySocketServer.class);
private final Socket server;
// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;
private StringBuffer buffHeartbeatMessage = new StringBuffer().append((char) 0).append((char) 0).append((char) 0)
.append((char) 0).append((char) 0).append((char) 0);
private Heartbeat heartbeat = new Heartbeat(/* 60 */3000, buffHeartbeatMessage.toString());
public MySocketServer(Socket server) {
this.server = server;
}
#Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
BufferedOutputStream out = new HeartbeatBufferedOutputStream(this.server.getOutputStream(),
heartbeat)) {
final StreamListener listener = new StreamListener(in);
listener.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getID() == ActionEvent.ACTION_PERFORMED) {
if (event.getActionCommand().equals(StreamListener.ERROR)) {
logger.error("Problem listening to stream.");
listener.setShouldContinue(false);
stopRunning();
} else {
String messageIn = event.getActionCommand();
if (messageIn == null) { // End of Stream;
stopRunning();
} else { // hey, we can do what we were meant for
logger.debug("Request received from client");
// doing stuff here
...
// done doing stuff
logger.debug("Sending Client Response");
try {
sendResponse(opResponse, out);
} catch (Exception ex) {
logger.error("Error sending response to OP.", ex);
}
}
}
}
}
});
listener.start();
while (shouldContinue) {
// loop here until shouldContinue = false;
// this should be set to false in the ActionListener above
}
heartbeat.setShouldStop(true);
return;
} catch (Exception ex) {
logger.error("Error in ESPSocketServer", ex);
return;
}
}
private void stopRunning() {
shouldContinue = false;
}
private void sendResponse(ClientResponse opResponse, BufferedOutputStream out) throws Exception {
logger.debug("Before write");
out.write(opResponse.getResponse().getBytes());
logger.debug("After write. Before flush");
out.flush();
logger.debug("After flush");
// this log message is in my logs, so I know the message was sent
}
}
My StreamListener class.
public class StreamListener extends Thread {
protected final static Logger logger = LogManager.getLogger(StreamListener.class);
public final static String ERROR = "ERROR";
private BufferedReader reader = null;
private List<ActionListener> actionListeners = new ArrayList<>();
private boolean shouldContinue = true;
public StreamListener(BufferedReader reader) {
this.reader = reader;
}
#Override
public void run() {
while (shouldContinue) {
String message;
try {
// client blocks here and never receives message
message = reader.readLine();
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, message);
fireActionPerformed(event);
} catch (IOException e) {
e.printStackTrace();
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ERROR);
fireActionPerformed(event);
}
}
}
public void setShouldContinue(boolean shouldContinue) {
this.shouldContinue = shouldContinue;
}
public boolean getShouldContinue() {
return shouldContinue;
}
public boolean addActionListener(ActionListener listener) {
return actionListeners.add(listener);
}
public boolean removeActionListener(ActionListener listener) {
return actionListeners.remove(listener);
}
private void fireActionPerformed(ActionEvent event) {
for (ActionListener listener : actionListeners) {
listener.actionPerformed(event);
}
}
}
My Heartbeat class
public class Heartbeat extends Thread {
private BufferedOutputStream bos = null;
private int beatDelayMS = 0;
private String message = null;
private boolean shouldStop = false;
public Heartbeat(int beatDelayMS, String message) {
this.beatDelayMS = beatDelayMS;
this.message = message;
setDaemon(true);
}
#Override
public void run() {
if (bos == null) { return; }
while(!shouldStop) {
try {
sleep(beatDelayMS);
try {
bos.write(message.getBytes());
bos.flush();
} catch (IOException ex) {
// fall thru
}
} catch (InterruptedException ex) {
if (shouldStop) {
return;
}
}
}
}
public void setBufferedOutputStream(BufferedOutputStream bos) {
this.bos = bos;
}
public BufferedOutputStream getBufferedOutputStream() {
return bos;
}
public void setShouldStop(boolean shouldStop) {
this.shouldStop = shouldStop;
}
public boolean getShouldStop() {
return shouldStop;
}
}
My HeartbeatBufferedOutputStream
public class HeartbeatBufferedOutputStream extends BufferedOutputStream {
private Heartbeat heartbeat = null;
public HeartbeatBufferedOutputStream(OutputStream out, Heartbeat heartbeat) {
super(out);
this.heartbeat = heartbeat;
this.heartbeat.setBufferedOutputStream(this);
heartbeat.start();
}
#Override
public synchronized void flush() throws IOException {
super.flush();
heartbeat.interrupt();
}
}
And finally here is the "Client" class
public class Mockup extends Thread {
protected final static Logger logger = LogManager.getLogger(Mockup.class);
// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;
public static void main(String[] args) {
new Mockup().start();
}
#Override
public void run() {
try (Socket socket = new Socket("localhost", 16100);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
final StreamListener listener = new StreamListener(in);
listener.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getID() == ActionEvent.ACTION_PERFORMED) {
if (event.getActionCommand().equals(StreamListener.ERROR)) {
logger.error("Problem listening to stream.");
listener.setShouldContinue(false);
stopRunning();
} else {
String messageIn = event.getActionCommand();
if (messageIn == null) { // End of Stream;
stopRunning();
} else { // hey, we can do what we were meant for
// convert the messageIn to an OrderPower request, this parses the information
logger.info("Received message from server. [" + messageIn + "].");
}
}
}
}
});
listener.start();
StringBuffer buff = new StringBuffer("Some message to send to server");
logger.info("Sending message to server [" + buff.toString() + "]");
out.write(buff.toString().getBytes());
out.flush();
boolean started = false;
while (shouldContinue) {
if (!started) {
logger.debug("In loop");
started = true;
}
// loop here until shouldContinue = false;
// this should be set to false in the ActionListener above
}
logger.info("Exiting Mockup");
return;
} catch (Exception ex) {
logger.error("Error running MockupRunner", ex);
}
}
private void stopRunning() {
shouldContinue = false;
}
}
I have confirmed from logging messages that the Server sends a message to the BufferedOutputStream, and is flushed, but the Client logs indicate that it is blocked on the reader.readLine() and never gets the message.
You are reading lines but you are never writing lines. Add a line terminator to what you send.
I am working on Client/Server chat and am having issues removing the name from the list on all the open clients when one client disconnects. Right I have it where it seems like it broadcasting the list between the clients but its not removing any of the name. Any help would be awesome. This project is worth 50% of my final grade.
Chat Server Code:
class ChatHandler extends Thread
{ public ChatHandler(Socket i, ArrayList<ChatHandler> h)
{
incoming = i;
handlers = h;
handlers.add(this);
try{
in = new ObjectInputStream(incoming.getInputStream());
out = new ObjectOutputStream(incoming.getOutputStream());
}catch(IOException ioe){
System.out.println("Could not create streams.");
}
}
public synchronized void broadcast(){
ChatHandler left = null;
for(ChatHandler handler : handlers){
ChatMessage cm = new ChatMessage();
cm.setMessage(myObject.getMessage());
cm.setName(myObject.getName());
try{
handler.out.writeObject(cm);
System.out.println("Writing to handler outputstream: " + cm.getMessage());
}catch(IOException ioe){
//one of the other handlers hung up
left = handler; // remove that handler from the arraylist
}
}
handlers.remove(left);
if(myObject.getMessage().equals("bye")){ // my client wants to leave
done = true;
handlers.remove(this);
System.out.println("Removed handler. Number of handlers: " + handlers.size());
}
System.out.println("Number of handlers: " + handlers.size());
}
public void run()
{
try{
while(!done){
myObject = (ChatMessage)in.readObject();
System.out.println("Message read: " + myObject.getMessage());
broadcast();
}
} catch (IOException e){
if(e.getMessage().equals("Connection reset")){
System.out.println("A client terminated its connection.");
}else{
System.out.println("Problem receiving: " + e.getMessage());
}
}catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}finally{
handlers.remove(this);
}
}
Client Code:
public void actionPerformed(ActionEvent ae){
//TF ACTION LISTENER
if (ae.getSource()== tf){
if (connected) {
myObject = new ChatMessage();
myObject.setMessage(tf.getText());
myObject.setName(name);
tf.setText("");
try{
myOutputStream.reset();
myOutputStream.writeObject(myObject);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}else{
name = tf.getText();
setName(name);
}
}
//BUTTONS
if (ae.getSource()== connect){
connected = true;
name = tf.getText();
setName(name);
try{
scan = new Scanner(System.in);
myObject = new ChatMessage();
socketToServer = new Socket("127.0.0.1", 4001);
myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream());
myInputStream = new ObjectInputStream(socketToServer.getInputStream());
start();
}
catch(Exception e){
System.out.println(e.getMessage());
}
name = tf.getText();
setName(name);
myObject = new ChatMessage();
myObject.setMessage(getName() + " has connected");
myObject.setName(name);
tf.setText("");
try{
myOutputStream.reset();
myOutputStream.writeObject(myObject);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
disconnect.setEnabled(true);
}
if(ae.getSource()== disconnect){
connected = false;
myObject = new ChatMessage();
myObject.setMessage(getName() + " has disconnected");
myObject.setName(name);
myObject.setRemoveName(Clientlist);
tf.setText("");
try{
myOutputStream.reset();
myOutputStream.writeObject(myObject);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
/*
String[] items = Clientlist.getItems();
for (String s: items){
if(s.equals(myObject.getName())){
RemoveFrom = true;
}
}
if(RemoveFrom == true){
Clientlist.remove(myObject.getName());
}*/
try{
myObject.setRemoveName(Clientlist);
socketToServer.close();
myOutputStream.close();
myInputStream.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
public void run(){
System.out.println("Listening for messages from server . . . ");
try{
while(!receivingdone){
myObject = (ChatMessage)myInputStream.readObject();
ta.append(myObject.getName() + ": " + myObject.getMessage() + "\n");
String[] items = Clientlist.getItems();
boolean inList = false;
for (String s : items){
if (s.equals(myObject.getName()))
{ inList = true; }
}
if (inList == false) {
Clientlist.add(myObject.getName());
}
if (connected == false){
for (String s: items){
if(s.equals(myObject.getName())){
RemoveFrom = true;
}
}
if(RemoveFrom == true){
Clientlist.remove(myObject.getName());
}
}
}
}catch(IOException ioe){
System.out.println("IOE: " + ioe.getMessage());
}catch(ClassNotFoundException cnf){
System.out.println(cnf.getMessage());
}
}
Chat Message Code:
import java.io.*;
import java.awt.*;
public class ChatMessage implements Serializable{
public String name;
public String message;
public List list;
public ChatMessage(){}
public ChatMessage(String name, String message){
setName(name);
setMessage(message);
setRemoveName(list);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
public void setRemoveName(List list){
list.remove(getName());
this.list = list;
}
public List getRemoveName(){
return list;
}
}
Week before this code working perfectly but after formating the system it is giving NoSuchPortException while trying to send sms connect my nokia c3 cell phone via usb
error log is as
enter code here`INFO: Server startup in 17344 ms
+919032055002 null
problem is here in getting port number
javax.comm.NoSuchPortException
Port id is : null
at javax.comm.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:105)
at com.gces.sms.SerialConnection.openConnection(SerialConnection.java:73)
at com.gces.sms.Sender.send(Sender.java:68)
at com.gces.sms.SMSClient.run(SMSClient.java:38)
at java.lang.Thread.run(Unknown Source)
in sms client & msg is : null
java.lang.NullPointerException
at com.gces.sms.SerialConnection.openConnection(SerialConnection.java:90)
at com.gces.sms.Sender.send(Sender.java:68)
at com.gces.sms.SMSClient.run(SMSClient.java:38)
at java.lang.Thread.run(Unknown Source)
and code is here
package com.gces.sms;
import javax.comm.*;
import java.io.*;
import java.awt.TextArea;
import java.awt.event.*;
import java.util.TooManyListenersException;
public class SerialConnection implements SerialPortEventListener,
CommPortOwnershipListener {
private SerialParameters parameters;
private OutputStream os;
private InputStream is;
private KeyHandler keyHandler;
private CommPortIdentifier portId;
private SerialPort sPort;
private boolean open;
private String receptionString="";
public String getIncommingString(){
byte[] bVal= receptionString.getBytes();
receptionString="";
return new String (bVal);
}
public SerialConnection(SerialParameters parameters) {
this.parameters = parameters;
open = false;
}
public void openConnection() throws SerialConnectionException {
try {
portId = CommPortIdentifier.getPortIdentifier(parameters.getPortName());
} catch (NoSuchPortException e) {
System.out.println("problem is here in getting port number");
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Port id is : "+portId);
try {
sPort = (SerialPort)portId.open("SMSConnector", 30000);
} catch (PortInUseException e) {
throw new SerialConnectionException(e.getMessage());
}
sPort.sendBreak(1000);
try {
setConnectionParameters();
} catch (SerialConnectionException e) {
sPort.close();
throw e;
}
try {
os = sPort.getOutputStream();
is = sPort.getInputStream();
} catch (IOException e) {
sPort.close();
throw new SerialConnectionException("Error opening i/o streams");
}
try {
sPort.addEventListener(this);
} catch (TooManyListenersException e) {
sPort.close();
throw new SerialConnectionException("too many listeners added");
}
sPort.notifyOnDataAvailable(true);
try {
sPort.enableReceiveTimeout(30);
} catch (UnsupportedCommOperationException e) {
}
portId.addPortOwnershipListener(this);
open = true;
}
public void setConnectionParameters() throws SerialConnectionException {
int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();
try {
sPort.setSerialPortParams(parameters.getBaudRate(),
parameters.getDatabits(),
parameters.getStopbits(),
parameters.getParity());
} catch (UnsupportedCommOperationException e) {
parameters.setBaudRate(oldBaudRate);
parameters.setDatabits(oldDatabits);
parameters.setStopbits(oldStopbits);
parameters.setParity(oldParity);
throw new SerialConnectionException("Unsupported parameter");
}
try {
sPort.setFlowControlMode(parameters.getFlowControlIn()
| parameters.getFlowControlOut());
} catch (UnsupportedCommOperationException e) {
throw new SerialConnectionException("Unsupported flow control");
}
}
public void closeConnection() {
if (!open) {
return;
}
if (sPort != null) {
try {
os.close();
is.close();
} catch (IOException e) {
System.err.println(e);
}
sPort.close();
portId.removePortOwnershipListener(this);
}
open = false;
}
public void sendBreak() {
sPort.sendBreak(1000);
}
public boolean isOpen() {
return open;
}
public void serialEvent(SerialPortEvent e) {
StringBuffer inputBuffer = new StringBuffer();
int newData = 0;
switch (e.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
while (newData != -1) {
try {
newData = is.read();
if (newData == -1) {
break;
}
if ('\r' == (char)newData) {
inputBuffer.append('\n');
} else {
inputBuffer.append((char)newData);
}
} catch (IOException ex) {
System.err.println(ex);
return;
}
}
receptionString=receptionString+ (new String(inputBuffer));
break;
case SerialPortEvent.BI:
receptionString=receptionString+("\n--- BREAK RECEIVED ---\n");
}
}
public void ownershipChange(int type) {
/*
if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED) {
PortRequestedDialog prd = new PortRequestedDialog(parent);
}
*/
}
class KeyHandler extends KeyAdapter {
OutputStream os;
/**
Creates the KeyHandler.
#param os The OutputStream for the port.
*/
public KeyHandler(OutputStream os) {
super();
this.os = os;
}
/**
Handles the KeyEvent.
Gets the <code>char</char> generated by the <code>KeyEvent</code>,
converts it to an <code>int</code>, writes it to the <code>
OutputStream</code> for the port.
*/
public void keyTyped(KeyEvent evt) {
char newCharacter = evt.getKeyChar();
if ((int)newCharacter==10) newCharacter = '\r';
System.out.println ((int)newCharacter);
try {
os.write((int)newCharacter);
} catch (IOException e) {
System.err.println("OutputStream write error: " + e);
}
}
}
public void send(String message) {
byte[] theBytes= (message+"\n").getBytes();
for (int i=0; i<theBytes.length;i++){
char newCharacter = (char)theBytes[i];
if ((int)newCharacter==10) newCharacter = '\r';
try {
os.write((int)newCharacter);
} catch (IOException e) {
System.err.println("OutputStream write error: " + e);
}
}
//System.out.println (">'" +message +"' sent");
}
}
and the second file code is as
package com.gces.sms;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;
import com.gces.sms.SerialConnection;
import com.gces.sms.SerialConnectionException;
import com.gces.sms.SerialParameters;
public class Sender implements Runnable {
private static final long STANDARD=500;
private static final long LONG=2000;
private static final long VERYLONG=20000;
SerialConnection mySerial =null;
static final private char cntrlZ=(char)26;
String in, out;
Thread aThread=null;
private long delay=STANDARD;
String recipient=null;
String message=null;
//private String csca="+919084051550"; // the message center uninor
//private String csca="+919837099995"; // the message center idea
private String csca="+919032055002"; // the message center docomo
private SerialParameters defaultParameters= new SerialParameters ("COM4",9600,0,0,8,1,0);
public int step;
public int status=-1;
public long messageNo=-1;
public Sender(String recipient, String message){
this.recipient=recipient;
this.message=message;
}
public int send () throws Exception {
File file = new File("C:\\db_backup\\SMS.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
String port = null;
int flag=0;
while( (line = br.readLine())!= null ){
if(flag==0)
port=line;
else if(flag==1)
csca=line;
else
br.close();
flag++;
}
//br.close();
defaultParameters= new SerialParameters (port,9600,0,0,8,1,0);
SerialParameters params = defaultParameters;
System.out.println(csca+" "+port);
mySerial =new SerialConnection (params);
mySerial.openConnection();
aThread=new Thread(this);
aThread.start() ;
//log("start");
return 0;
}
public void run(){
boolean timeOut=false;
long startTime=(new Date()).getTime();
while ((step <7) && (!timeOut)){
timeOut=((new Date()).getTime() - startTime)>delay;
//if atz does not work, type to send cntrlZ and retry, in case a message was stuck
if (timeOut && (step==1)) {
step=-1;
mySerial.send( ""+cntrlZ);
}
//read incoming string
String result= mySerial.getIncommingString() ;
//System.out.println("<- in rrrrrrrrrr "+result+"\n--------");
int expectedResult=-1;
try{
//log ("Step:"+step);
switch (step){
case 0:
mySerial.send("atz");
delay=LONG;
startTime=(new Date()).getTime();
break;
case 1:
delay=STANDARD;
mySerial.send("ath0");
startTime=(new Date()).getTime();
break;
case 2:
expectedResult=result.indexOf("OK");
//log ("received ok ="+expectedResult);
if (expectedResult>-1){
mySerial.send("at+cmgf=1");
startTime=(new Date()).getTime();
}else{
step=step-1;
}
break;
case 3:
expectedResult=result.indexOf("OK");
// log ("received ok ="+expectedResult);
if (expectedResult>-1){
mySerial.send("at+csca=\""+csca+"\"");
startTime=(new Date()).getTime();
}else{
step=step-1;
}
break;
case 4:
expectedResult=result.indexOf("OK");
// log ("received ok ="+expectedResult);
if (expectedResult>-1){
mySerial.send("at+cmgs=\""+recipient+"\"");
startTime=(new Date()).getTime();
}else{
step=step-1;
}
break;
case 5:
expectedResult=result.indexOf(">");
//log ("received ok ="+expectedResult);
if (expectedResult>-1){
mySerial.send(message+cntrlZ);
startTime=(new Date()).getTime();
}else{
step=step-1;
}
delay=VERYLONG;//waiting for message ack
break;
case 6:
expectedResult=result.indexOf("OK");
//read message number
if (expectedResult>-1){
int n=result.indexOf("CMGS:");
result=result.substring(n+5);
//System.out.println(result);
n=result.indexOf("\n");
status=0;
// result="1 11";
try{
messageNo=Long.parseLong(result.substring(0,n).trim() );
}
catch(NumberFormatException e){
//result="1 ";
messageNo=1;
}
log ("sent message no:"+messageNo);
}else{
step=step-1;
}
break;
}
step=step+1;
aThread.sleep(100);
}catch (Exception e){
e.printStackTrace();
}
}
mySerial.closeConnection() ;
//if timed out set status
if (timeOut ) {
status=-2;
log("*** time out at step "+step+"***");
}
}
private void log(String s){
System.out.println (new java.util.Date()+":"+this.getClass().getName()+":"+s);
}
}
This code working fine but after formating the system gives these error ...
I am currently developing chat application working over Internet.currently my application working fine over LAN but not working over Internet.I have also used port forwarding.I have done setting in modem and forward the port to private IP address but still it's not working.I got the error that "server isn't found".Please suggest me what I have to do and tell,Am I done the correct setting in modem or not??
Below is my server code...
Server.java
import java.util.*;
import java.net.*;
import java.io.*;
class Server implements ChatConstants
{
private static Vector list;
private ServerSocket ssocket ;
private Service service;
private static Socket socket;
private boolean done=false;
private static Hashtable userTable = new Hashtable();
private static Hashtable _userList = new Hashtable();
private static Hashtable _conflist = new Hashtable();
public Server() throws UnknownHostException
{
System.out.println("Initializing...");
list=new Vector(BACKLOG);
try {
ssocket= new ServerSocket(SERVER_PORT,BACKLOG);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Inside constructor"+e);
}
start();
}
public void start() throws UnknownHostException
{
byte[] data;
int header;
Socket _socket = null;
String hostname = null;
System.out.println("Server successfully started at "
+InetAddress.getLocalHost().toString()
+" port "+SERVER_PORT);
while(!done) {
try
{
_socket=ssocket.accept();
if(_socket != null) {
synchronized(list) {
list.addElement(_socket);
}
DataInputStream dis=new DataInputStream(_socket.getInputStream());
data = new byte[MAX_MESSAGE_SIZE];
dis.read(data);
Message message = ((Message)ChatUtils.bytesToObject(data));
System.out.println("Joined client "
+message._username+" at "+message._host+"...");
synchronized(userTable) {
userTable.put(message._username,_socket);
}
addUser(message);
sendUserList(message);
writeToClients(message);
service = new Service(_socket,hostname,message._user);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Thread exception"+e);
try {
_socket.close();
}
catch(Exception ex) {
ex.printStackTrace();
System.out.println("ERROR CLOSING SOCKET");
}
}
}//END WHILE
}
private void addUser(Message message)
{
synchronized(_userList) {
_userList.put(message._user.toString(),message._user);
}
}
public static void updateUser(User user)
{
User myuser;
synchronized(_userList) {
_userList.put(user.toString(),user);
}
}
public static synchronized void writeToClients(Message message)
{
byte[] data;
DataOutputStream dos;
for(int count=0;count<list.size();count++) {
try {
dos=new
DataOutputStream(((Socket)list.elementAt(count)).getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Output exception");
}
}//END FOR
}
public static void writeToClient(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(userTable) {
try {
socket = (Socket)userTable.get(message._destination);
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("SEND EXCEPTION"+e);
}
}
}
public static void sendConferenceListToClient(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(userTable) {
try {
Message mymessage= new Message(CONFERENCE_LIST);
Vector vector = (Vector)
_conflist.get(message._destination);
mymessage._username = message._username;
mymessage._destination = message._destination;
mymessage.userlist = vector;
socket = (Socket)userTable.get(message._username);
if(socket!=null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(mymessage);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("CONFERENCE LIST EXCEPTION"+e);
}
}
}
public static void writeToPublicChat(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(_conflist) {
try {
Vector svector = (Vector)_conflist.get(message._destination);
for(int cnt=0;cnt<svector.size();cnt++) {
synchronized(userTable) {
try {
socket = (Socket)userTable.get((svector.get(cnt).toString()));
if(socket!=null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("PUBLIC CHAT EXCEPTION"+e);
}
}
}
} catch(Exception e){
e.printStackTrace();
System.out.println("PUBLIC EXCEPTION"+e);
}
}
}
public static void inviteToPublicChat(Vector svector,Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(_conflist) {
for(int cnt=0;cnt<svector.size();cnt++) {
synchronized(userTable) {
try {
socket = (Socket)userTable.get((svector.get(cnt).toString()));
if(socket != null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("PUBLIC INVITE EXCEPTION"+e);
}
}
}
}
}
private void sendUserList(Message message)
{
int header=0;
String destination;
header=message._header;
destination = message._destination;
message._header = USERS_LIST;
message._destination = message._username;
message.userlist = new Vector(_userList.values());
writeToClient(message);
//Restore the headers
message._destination = destination;
message._header = header;
}
public static synchronized void removeUser(User user)
{
try {
Socket socket = (Socket)userTable.get(user.toString());
list.removeElement(socket);
_userList.remove(user.toString());
userTable.remove(user.toString());
}
catch(Exception e) {
e.printStackTrace();
System.out.println("ERROR REMOVING SOCKET "+e);
}
}
public static synchronized void processClientMessage(Message message)
{
switch(message._header) {
case CHANGE_STATUS:
updateUser(message._user);
writeToClients(message);
break;
case CLIENT_LOGOUT:
removeUser(message._user);
writeToClients(message);
break;
case CONFERENCE_CREATE:
Vector myvector = new Vector();
myvector.add(message._username);
_conflist.put(message._user.toString(),myvector);
case CONFERENCE_INVITE:
inviteToPublicChat(message.userlist,message);
break;
case CONFERENCE_JOIN:
Vector vector=null;
vector = (Vector)
_conflist.get(message._destination.toString());
vector.add(message._username);
_conflist.put(message._destination.toString(),vector);
writeToPublicChat(message);
break;
case CONFERENCE_DENY:
//_conflist.remove(message._user.toString(),message.userlist);
writeToPublicChat(message);
break;
case CONFERENCE_LEAVE:
Vector vectors =(Vector)
_conflist.get(message._destination.toString());
for(int count=0;count<vectors.size();count++) {
if(message._username.equals((vectors.elementAt(count).toString())))
vectors.remove(count);
}
if(vectors.size() != 0)
_conflist.put(message._user.toString(),vectors);
else//IF THERE ARE NO MORE USERS
_conflist.remove(message._user.toString());//DONE CONFERENCE
writeToPublicChat(message);
break;
case PUBLIC_CHAT:
writeToPublicChat(message);
break;
case CONFERENCE_LIST:
sendConferenceListToClient(message);
break;
default:
writeToClient(message);
}
}
public static void main(String args[]) throws Exception
{
Server chatserver=new Server();
}
}
//
// Service: Service class for each clients connected to server.
//
class Service implements Runnable, ChatConstants
{
private DataInputStream dis;
private Socket socket;
private boolean done=false;
private Thread thread;
private String hostname;
private User user;
public Service(Socket _socket,String _hostname,User user)
{
try {
this.socket = _socket;
this.hostname=_hostname;
this.user = user;
dis=new DataInputStream(socket.getInputStream());
thread=new Thread(this,"SERVICE");
thread.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("service constructor"+e);
}
}
public void run()
{
byte[] data;
while(!done)
{
try {
data = new byte[MAX_MESSAGE_SIZE];
dis.read(data);
Message message = ((Message)ChatUtils.bytesToObject(data));
Server.processClientMessage(message);
}
catch(Exception e) {
e.printStackTrace();
done = true;
Server.removeUser(user);
Message message = new Message(CLIENT_LOGOUT);
user.isOnline = OFFLINE;
message._user = user;
Server.writeToClients(message);
try {
socket.close();
} catch(Exception se) {
se.printStackTrace();
System.out.println("ERROR CLOSING SOCKET "+se);
}
//System.out.println("SERVICE THREAD EXCEPTION"+e);
}
}//END WHILE
}
}
Thanks in advance.
I think the
ssocket= new ServerSocket(SERVER_PORT,BACKLOG);
is making the issue. Use the version
ssocket= new ServerSocket(SERVER_PORT,BACKLOG,LOCAL_INET_ADDRESS);
and bind server to some constant local IP. Now use the port forwarding in the modem, to forward all requests to that local ip. Make sure that the firewall is not preventing you to use the port. Since firewall may allow a local networking but not to web.