Thread: online game
View Single Post
Old Apr 17th, 2008, 4:49 PM   #6
cwl157
Professional Programmer
 
Join Date: Feb 2005
Posts: 327
Rep Power: 4 cwl157 is on a distinguished road
Re: online game

so to start i am just trying to make 2 clients and a server. The clients will connect to the server and pass a message from one client to the other and it is not working right. The message never gets sent and the server and both clients just hang. Do i need a different name for the different client Sockets? If so I don't know how i would do this because both people playing will be running exact copies of the same program and connect to the server and then the server passes messages between them.

Here is the server code i have
java Syntax (Toggle Plain Text)
  1. import java.net.*;
  2. import java.io.*;
  3.  
  4. public class Server
  5. {
  6. public static void main(String[] args) throws IOException
  7. {
  8. ServerSocket srvr = new ServerSocket(1234);
  9. Socket skt1 = new Socket();
  10.  
  11. skt1 = srvr.accept();
  12. System.out.print("Server has connected!\n");
  13. skt1 = srvr.accept();
  14. System.out.print("Server has connected!\n");
  15.  
  16. // network IO for client
  17. PrintWriter out1 = new PrintWriter(skt1.getOutputStream(), true);
  18. BufferedReader in1 = new BufferedReader(
  19. new InputStreamReader(
  20. skt1.getInputStream()));
  21. String line = null;
  22. line = in1.readLine();
  23. out1.println(line);
  24.  
  25.  
  26. out1.close();
  27. in1.close();
  28. skt1.close();
  29. } // end main
  30. } // end class Server
here is the client code I have
java Syntax (Toggle Plain Text)
  1. import java.io.*;
  2. import java.net.*;
  3.  
  4. public class Client {
  5. public static void main(String[] args) throws IOException
  6. {
  7. Socket skt1 = new Socket("Carl1", 1234);
  8. PrintWriter out = new PrintWriter(skt1.getOutputStream(), true);
  9. BufferedReader in = new BufferedReader(new InputStreamReader(
  10. skt1.getInputStream()));
  11.  
  12.  
  13. String line = "Send this to the other client";
  14. while(true)
  15. {
  16. try
  17. {
  18. line = in.readLine();
  19. System.out.println(line);
  20. out.println(line);
  21. } // end try
  22. //catches bad user input and throws exception
  23. catch (NumberFormatException ex)
  24. {
  25. System.out.print("Error bad data: ");
  26. } // end catch
  27. } // end while
  28. } // end main
  29. } // end Client

I want the one client to send the String line to the server and then the server to pass it to the second client. This is like how the battleship game will work one player sends the row and column he wants to hit and the server sends that information to the other client.
cwl157 is offline   Reply With Quote