Thread: online game
View Single Post
Old Apr 19th, 2008, 9:50 AM   #12
BinarySurfer
Programmer
 
BinarySurfer's Avatar
 
Join Date: Dec 2006
Posts: 50
Rep Power: 2 BinarySurfer is on a distinguished road
Re: online game

@Freaky Chris
I've never done it that way. A better way might be to make the socket public or the send method public. Then, in the other applications, you can call the class that has the connection and use the connection or call the send class.
java Syntax (Toggle Plain Text)
  1. ServerClass.send("something");
I could be wrong because I have not tested it to know for myself. I have only used that accessed variable from one class to other classes, but I think the logic would work.

@cwl157
Sorry, I only got to send you the sever class, but the server looks right. The client does have to be redesigned. Not implementing what you need, here's the bare bones of the client
java Syntax (Toggle Plain Text)
  1. private Socket client
  2. private ObjectOutputStream output;
  3. private ObjectInputStream input;
  4.  
  5. private void client(){
  6. try{
  7. connect();
  8. streams();
  9. processConnection();
  10. }
  11. catch (EOFException eofException){
  12. System.err.println("Client terminated connection");
  13. }
  14. catch (IOException ioException){
  15. ioException.printStackTrace();
  16. }
  17. finally{
  18. closeConnection();
  19. }
  20. }
  21. private void connect() throws IOException{
  22. System.out.print("Attempting Connection\n");
  23. client = new Socket(InetAddress.getByName(192.168.1.102), 1234);
  24. System.out.print("Connected to: " + client.getInetAddress().getHostName());
  25. }
  26. private void streams() throws IOException{
  27. output=new ObjectOutputStream(client.getOutputStream());
  28. output.flush();
  29. input=new ObjectInputStream(client.getInputStream());
  30. System.out.print("\nStreams Estabolished\n");
  31. }
  32. private void processConnection() throws IOException{
  33. String test = ""
  34. do{
  35. try{
  36. test = (String)input.readObject();
  37. System.out.print("\n" + test);
  38. }
  39. catch(ClassNotFoundException classNotFoundException){
  40. System.out.print("\nUnknown object recieved");
  41. }
  42. }while(!test.equals("Server Connection Lost"));
  43. }
  44. private void closeConnection(){
  45. try{
  46. output.close();
  47. input.close();
  48. client.close();
  49. }
  50. catch(IOException ioException){
  51. ioException.printStackTrace();
  52. }
  53. }
  54. private void sendData(String data){
  55. try{
  56. output.writeObject(data);
  57. output.flush();
  58. }
  59. catch(IOException ioException){
  60. System.out.print("\nError writing object");
  61. }
  62. }
That should do it.

Last edited by BinarySurfer; Apr 19th, 2008 at 9:52 AM. Reason: Forgot to inicialize 2 objects
BinarySurfer is offline   Reply With Quote