I'm trying to write a simple client/server application. I have a data on a client's side, that turns into an integer array and transfers to server. The server makes the calcutaions and returns them to client. But my program falls with this exception.
Sorry for long text, I'm just studying and really need your help.
public class Client {
private static Socket clientSocket;
private static ObjectInputStream in;
private static ObjectOutputStream out;
private static int[] parsedValue;
public Client(String input) {
try {
parsedValue = Arrays.stream(input.split(",")).mapToInt(Integer::parseInt).toArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public Client(int[] input) {
parsedValue = input;
}
public Client(List<Integer> input) {
try {
parsedValue = input.stream().mapToInt(d->d).toArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
try {
clientSocket = new Socket("localhost", 4004);
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
String clientTestString = "440,5,16";
Client stringClient = new Client(clientTestString);
out.writeObject(stringClient.parsedValue);
out.flush();
System.out.println(in.readObject());
int[] clientIntsTest = {39, 10, 5};
Client arrayClient = new Client(clientIntsTest);
out.writeObject(arrayClient.parsedValue);
out.flush();
System.out.println(in.readObject());
List<Integer> clientsTestList = Arrays.asList(781, 9, 7);
Client listClient = new Client(clientsTestList);
out.writeObject(listClient.parsedValue);
out.flush();
System.out.println(in.readObject());
} finally {
System.out.println("Client was closed");
clientSocket.close();
in.close();
out.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
}
public class Server {
private static Socket clientSocket;
private static ServerSocket server;
private static ObjectInputStream in;
private static ObjectOutputStream out;
private static int[] parsedValue;
public String getResult() {
return calculation(parsedValue);
}
public String calculation(int[] parsedValue) {
parsedValue[0] = toDecimal(parsedValue[0], parsedValue[1]);
String answer = "";
int temp = 0;
String digits = new String("ABCDEF");
while (parsedValue[0] > 0) {
temp = parsedValue[0] % parsedValue[2];
if (temp < 10) {
answer = temp + answer;
} else {
answer = digits.charAt(temp - 10) + answer;
}
parsedValue[0] /= parsedValue[2];
}
return answer;
}
public int toDecimal(int value, int baseNotation) {
int i = 0;
int decimalNumber = 0;
if (value > 0) {
while (value != 0) {
decimalNumber += (value % 10) * Math.pow(baseNotation, i);
value /= 10;
i++;
}
}
return decimalNumber;
}
public static void main(String[] args) {
try {
try {
server = new ServerSocket(4004);
System.out.println("Server runs");
clientSocket = server.accept();
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
parsedValue = (int[]) in.readObject();
System.out.println(parsedValue);
Server examp = new Server();
String answer = examp.getResult();
System.out.println(answer);
out.writeObject(answer);
out.flush();
} finally {
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
}
In this two lines
Server examp = new Server();
String answer = examp.getResult();
you cretat a new object which overriddes the field private static ServerSocket server;
A better solution is to put the logic from your main() into a seperate method like run(), instantiate in main() a new object of server and call the run() on it. Dont't forget to make all fields as instance members by removing the static keyword.
public static void main(String[] args) {
Server examp = new Server();
examp.run();
}
public void run() {
try {
try {
server = new ServerSocket(4004);
System.out.println("Server runs");
clientSocket = server.accept();
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
parsedValue = (int[]) in.readObject();
System.out.println(parsedValue);
String answer = getResult();
System.out.println(answer);
out.writeObject(answer);
out.flush();
} finally {
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
By the way: You should always use this patern to get out of the 'static-trap'. So I suggest you refactor your Client calss too.
I'm trying to work with multiThreading and I want to write a code that must do some operations on a specific file called data.txt.
There must be three writers and three readers,writer 1 has to write a random char from A to Z,writer 2 has to write a random number from 1 to 100,writer 3 has to write a random char from this set of characters {*%$##!&}.
Then readers must read a character from the file data.txt and then reader 1 write this character in file 1.txt,reader 2 write this character in file 2.txt and reader 3 write this character in file 3.txt.
If there was no character in data file to read the readers must wait until the writers add something to the data file.
I have wrote two classes called WriterInFile and ReaderFromFile that extends Thread class but it seems that the ReaderFromFile doesn't work correctly(It doesn't read any characters from data file and doesn't add anything to files 1.txt,2.txt,3.txt)
This is the code for ReaderFromFile class:
import java.io.*;
public class ReaderFromFile extends Thread {
private static FileReader reader;
private int numberOfReader;
ReaderFromFile(int numberOfReader, FileReader reader) {
this.numberOfReader = numberOfReader;
ReaderFromFile.reader = reader;
}
public void run() {
for (int i = 0; i < 5; i++) {
String s = null;
try {
s = readFrom();
} catch (IOException e) {
e.printStackTrace();
}
FileWriter writer;
switch (numberOfReader) {
case 1:
try {
writer = new FileWriter("1.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 2:
try {
writer = new FileWriter("2.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 3:
try {
writer = new FileWriter("3.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/**
* #return the character that has been reed
*/
private synchronized String readFrom() throws IOException {
String s = null;
while (!reader.ready()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
s = String.valueOf(reader.read());
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
return s;
}
}
this is the WriterInFile class:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class WriterInFile extends Thread {
private static FileWriter writer;
private int numberOfReader;
WriterInFile(int numberOfReader, FileWriter writer) {
this.numberOfReader = numberOfReader;
WriterInFile.writer = writer;
}
public void run() {
for (int i=0;i<5;i++){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (numberOfReader) {
case 1:
writeChar();
break;
case 2:
writeNumber();
break;
case 3:
writeShape();
break;
}
}
}
private synchronized void writeChar() {
String s = getRandomChar();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeNumber() {
String s = getRandomNumber();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeShape() {
String s = getRandomShape();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private String getRandomChar() {
double randomDouble = Math.random();
randomDouble = randomDouble * 26;
int randomInt = (int) randomDouble;
return String.valueOf((char)(randomInt+'A'));
}
private String getRandomNumber() {
double randomDouble = Math.random();
randomDouble = randomDouble * 100 + 1;
int randomInt = (int) randomDouble;
return String.valueOf(randomInt);
}
private String getRandomShape() {
String chars = "*%$##!&";
Random rnd = new Random();
char randomChar = chars.charAt(rnd.nextInt(chars.length()));
return String.valueOf(randomChar);
}
}
and this is the main file:
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("data.txt");
FileReader reader = new FileReader("data.txt");
//creating writers
WriterInFile writer1 = new WriterInFile(1, writer);
WriterInFile writer2 = new WriterInFile(2, writer);
WriterInFile writer3 = new WriterInFile(3, writer);
// creating readers
ReaderFromFile reader1 = new ReaderFromFile(1, reader);
ReaderFromFile reader2 = new ReaderFromFile(2, reader);
ReaderFromFile reader3 = new ReaderFromFile(3, reader);
writer1.start();
writer2.start();
writer3.start();
reader1.start();
reader2.start();
reader3.start();
Thread.sleep(10000);
writer.close();
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
When I run it goes to this file named niceJob.txt and the file that the data come from is called file2.txt which included
niceJob.txt 40
20 1 1 5 7 45 1 2 3 4 5 6 7 8 9 77 88 99 23 34 56
and when I open niceJob.txt it would show
X8
I am really confused as to why and how this is happening. Here is the code:
import java.io.*;
import java.util.Scanner;
public class JH1_00668860 {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of print
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
FileWriter ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + " asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileWriter(fileoutputname);
while (scan.hasNextInt()) {
if (scan.nextInt() >= 0) {
// System.out.println(scan.nextInt() + "asfs");
ps.write(scan.nextInt());
ps.flush();
} else {
System.out.println("You have ran out of data or you have a bad value");
}
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch (IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("file2.txt");
}
}
You are calling scan.nextInt() multiple times (2 times) in an iteration of while loop and using the second call of scan.nextInt() in writing to your file ps.write(scan.nextInt()); it skips every alternate integer
You are passing an integer to ps.write(), instead, pass a string
import java.util.Scanner;
import java.io.*;
public class Main {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of print
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
FileWriter ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + " asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileWriter(fileoutputname);
int currentInt = -1;
while (scan.hasNextInt()) {
currentInt = scan.nextInt();
if (currentInt >= 0) {
//System.out.println(currentInt + "asfs");
ps.write(String.valueOf(currentInt));
ps.flush();
} else {
System.out.println("You have ran out of data or you have a bad value");
}
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch (IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("sample.txt");
}
}
Output :
niceJob.txt asfasdfasdfasdf
A file was created
4020115745123456789778899233456
I'm having trouble getting my PrintStream to work correctly. I built a basic chatroom with commands (excuse my code if its messy, I just kind of threw it together) But the enter your name print statement only runs AFTER the name is inputted. So it hangs with a cursor until text is submitted then prints
Test (This is the input)
Enter your name:
Welcome to the channel Test. Current members: Test,
The first line is the input and the second and third is the resulting print statement. Is there a solution I'm missing? (All appropriate classes have been imported)
public class FinalProjectClientThread extends Thread
{
public DataInputStream is = null;
public PrintStream os = null;
public Socket clientSocket = null;
public final FinalProjectClientThread[] threads;
public int clientCount;
public String ClientName;
private boolean isModerator;
private boolean isMuted;
public FinalProjectClientThread(Socket clientSocket, FinalProjectClientThread[] threads)
{
this.clientSocket = clientSocket;
this.threads = threads;
clientCount = threads.length;
isModerator = false;
}
public String getClientName()
{
return ClientName;
}
private void setClientName(String n)
{
ClientName = n;
}
public void stopServer()
{
System.exit(0);
}
public void kickUser()
{
try
{
clientSocket.close();
}
catch(IOException e)
{
}
}
public void muteUser()
{
isMuted = true;
}
public void run()
{
int maxClients = this.clientCount;
FinalProjectClientThread[] threads = this.threads;
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.flush();
os.print("");
os.flush();
os.print("Enter your name: ");
os.flush();
String name = is.readLine();
this.setClientName(name);
os.print("\nWelcome to the channel " + name+". ");
os.flush();
//Count number of users in channel
int count = 0;
for(int i = 0; i < maxClients; i++)
{
if(threads[i]!=null&&threads[i].getClientName() != null)
{
count++;
}
}
//Print text based on number
if(count == 0)
{
os.println("There are no other members.");
os.flush();
}
else
{
os.print("Current members: ");
os.flush();
}
//Print member's names
for(int i = 0; i < maxClients; i++)
{
if(threads[i]!=null&&threads[i].getClientName() != null)
{
os.print(threads[i].getClientName()+ ", ");
os.flush();
}
}
os.println();
os.flush();
for(int i = 0; i < maxClients; i++)
{
if (threads[i] != null && threads[i] != this)
{
threads[i].os.println(name + " has joined the channel");
}
}
while (true)
{
String line = is.readLine();
if (line.equals("/leave"))
{
break;
}
else if(line.equals("/mod"))
{
os.println("Enter the moderator code: ");
String line2 = is.readLine();
if(line2.equals("hurricanemod"))
{
isModerator = true;
for (int i = 0; i < maxClients; i++)
{
if (threads[i] != null)
{
threads[i].os.println(name+" is now a moderator");
}
}
}
else
{
os.println("That code is incorrect");
}
}
else if(line.equals("/help"))
{
os.print("The following commands are valid: leave, help, mod, kick, mute, unmute");
}
else if(line.indexOf("/kick") == 0)
{
if(isModerator)
{
for(int i = 0; i < maxClients; i++)
{
if(threads[i] != null && threads[i].getClientName().equals(line.substring(6, line.length())))
{
threads[i].kickUser();
}
}
os.println("User kicked");
}
else
{
os.println("You must be a moderator to kick people. Use /mod and the code provided by the server hoster");
}
}
else if(line.equals("/stop"))
{
if(isModerator)
{
this.stopServer();
}
else
{
os.println("You must be a moderator to stop the server. Use /mod and the code provided by the server hoster");
}
}
else if(line.indexOf("/mute") == 0)
{
if(isModerator)
{
for(int i = 0; i < maxClients; i++)
{
if(threads[i] != null && threads[i].getClientName().equals(line.substring(6, line.length())))
{
threads[i].muteUser();
}
}
os.println(line.substring(6, line.length())+ " was muted.");
}
else
{
os.println("You must be a moderator to kick people. Use /mod and the code provided by the server hoster");
}
}
else
{
if(!isMuted)
{
for (int i = 0; i < maxClients; i++)
{
if (threads[i] != null)
{
threads[i].os.println(name+": " + line);
}
}
}
else
{
os.println("You are muted");
}
}
}
for (int i = 0; i < maxClients; i++)
{
if (threads[i] != null && threads[i] != this)
{
threads[i].os.println(name + " left the channel");
}
}
os.println("You have left the channel");
for (int i = 0; i < maxClients; i++)
{
if (threads[i] == this)
{
threads[i] = null;
}
}
is.close();
os.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("IOExcepetion(Thread)");
}
}
}
Server
public class FinalProjectServer
{
private static Scanner kb = new Scanner (System.in);
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static int clientCount = 10;
private static FinalProjectClientThread[] clientList = new FinalProjectClientThread[clientCount];
public static void main(String[] args)
{
/*System.out.print("Enter port for server to run on: ");
int port = kb.nextInt();*/
int port = 25565;
try
{
serverSocket = new ServerSocket(port);
}
catch(IOException e)
{
System.err.println("IOException");
}
while(true)
{
try
{
clientSocket = serverSocket.accept();
int i = 0;
for(i = 0; i < clientCount; i++)
{
if(clientList[i] == null)
{
clientList[i] = new FinalProjectClientThread(clientSocket,clientList);
clientList[i].start();
break;
}
}
if(i == clientCount)
{
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Max number of client reached. Please contact server host.");
os.close();
clientSocket.close();
}
}
catch(IOException e)
{
System.err.println(e);
}
}
}
}
Client
public class FinalProjectClient implements Runnable
{
private static Scanner kb = new Scanner(System.in);
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args)
{
System.out.print("Enter the IP of the host computer: ");
String IP = kb.nextLine();
System.out.print("Enter the port number: ");
int port = kb.nextInt();
try
{
clientSocket = new Socket(IP, port);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
catch(UnknownHostException e)
{
System.err.println("Can not find host, Unknown");
}
catch(IOException e)
{
System.err.println("IOException");
}
try
{
new Thread(new FinalProjectClient()).start();
while(!closed)
{
os.println(inputLine.readLine());
}
os.close();
is.close();
clientSocket.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
public void run()
{
String reply;
try
{
while((reply = is.readLine()) != null)
{
System.out.println(reply);
if(reply.indexOf("/leave") != -1)
break;
}
closed = true;
}
catch(IOException e)
{
System.err.println(e);
}
}
}
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.