Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (487)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (553)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Client & Server (first time need help) [FIXED]  (Read 1927 times)
0 Members and 1 Guest are viewing this topic.
Offline GabrielBailey74
« Posted 2012-04-20 05:36:40 »

I've never actually wrote a client & server in Java as a game yet, now i'm wanting to create and setup a client & server in Java so that I can do the following:

Send packets of TCP or UDP from server to client and vice versa. 0%?
Have a thread I guess? (never done this), but a constant game loop of transmitting packets back and forth. 50%
Being able to update the JFrame's JPanel according to the data received from the server. 0%

Guess that's it for now, really hope to get some feedback, I know how to setup a basic client & server to send data twice, once to the client, than back to the server, haven't really tried implementing a thread yet.

Just got done fixing it, I just added another 'while' loop to send data back to the Server, now the client stays open and sending Smiley

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2012-04-20 06:02:04 »

How to start threads:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
new Thread() {
    {
        start();
    }
   
    public void run() {
        //initialize socket stuffs
       
        while(keepSending) {
            //send and receive
       }
       
        //close the socket
   }
};


Most simplistic way of doing client-server games is to start a new thread for each client on the server.

Offline GabrielBailey74
« Reply #2 - Posted 2012-04-20 21:28:04 »

Here's what I got for the Server so far, yet everytime I run it (it creates a new thread fine), but it keeps saying 'Connection reset', after a new client connects.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
   // Constructor for the Server class.
  public Server() {
      running = true, keepSending = true;
      connect();
   }
   
   protected final void connect() {
      try {
         serverSocket = new ServerSocket(port);
         log(System.out, "Server listening on port: " + port + "...");
         new Thread() {
            {
               start();
            }

            public void run() {
               // Wait for client to connect on 4442
              try {
                  clientSocket = serverSocket.accept();
                  clientSocket.setSoLinger(true, MAX_PRIORITY);
                  log(System.out, "Connected a new Client!");
                  // Create a reader
                 bufferedReader = new BufferedReader(
                        new InputStreamReader(
                              clientSocket.getInputStream()));
                  // Get the client message
                 while ((inputLine = bufferedReader.readLine()) != null)
                     System.out.println(inputLine);
               } catch (SocketException e1) {
                  log(System.err, "Client disconnected!");
               } catch (IOException e) {
                  System.out.println(e);
               }
               // close the socket
              closeCons();
            }
         };
      } catch (IOException e) {
         log(System.err, e.getMessage());
      }
   }

   private static void closeCons() {
      try {
         serverSocket.close();
         clientSocket.close();
         bufferedReader.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

Here's the output in the console after launching the client:
Quote
Server listening on port: 4442...
Connected a new Client!
Hello Socket!
WOOOOOOOOOOOOO
Client disconnected!

It might have something to do with the Client class, yet it's still not sending the String?

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
   // Constructor for the Client class.
  public Client() {
      connect(port);
   }

   private void connect(int port2) {
      try {
         socket = new Socket("localhost", port2);
         log(System.out, "Client connected");
         log(System.out, socket);
         printWriter = new PrintWriter(socket.getOutputStream(), true);
         sendData("Hello Socket!");
         sendData("WOOOOOOOOOOOOO");
      } catch (SocketException e1) {
         log(System.err, "Client disconnected!??!");
      } catch (Exception e) {
         log(System.err, e.getMessage());
      }
   }


Both on the same ports, 4442, if anyone can see why it's not working correctly please let me know.
I'll continue to try and fix it, i'd like the Client not to disconnect.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #3 - Posted 2012-04-20 22:27:57 »

Well if you didn't suppress the SocketException, then you would find out why it closed Smiley

Offline GabrielBailey74
« Reply #4 - Posted 2012-04-20 22:31:19 »

Here's the consoles outprint of the stacktrace:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
java.net.SocketException: Connection reset
   at java.net.SocketInputStream.read(Unknown Source)
   at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
   at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
   at sun.nio.cs.StreamDecoder.read(Unknown Source)
   at java.io.InputStreamReader.read(Unknown Source)
   at java.io.BufferedReader.fill(Unknown Source)
   at java.io.BufferedReader.readLine(Unknown Source)
   at java.io.BufferedReader.readLine(Unknown Source)
   at server.util.connection.Server$1.run(Server.java:55)


And here's line 55:
1  
2  
3  
4  
// Get the client message
  while ((inputLine = bufferedReader.readLine()) != null) { // line 55.
     System.out.println(inputLine);
   }

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #5 - Posted 2012-04-20 22:38:58 »

Do you get any errors on the client? Do you ever close the connection on the client? Does the client JVM terminate without you close()-ing the connection?

Offline GabrielBailey74
« Reply #6 - Posted 2012-04-20 22:42:54 »

Client console after program launch:
1  
2  
Client connected
Socket[addr=localhost/127.0.0.1,port=4442,localport=57018]

Than it exits, might be because it's being called upon by a batch file?

1  
2  
3  
4  
5  
6  
7  
8  
9  
@echo off
@color 0a
@title Running: Client

:main
cls
java -Xmx800m -cp bin; server.util.connection.Client
pause
goto main


So, I start off by launching the Server in Eclipse, than I launch the Client via batch file, no exit called in either class.

Is it because the Client class has no active thread/loop?, just calls a simple try/catch.

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #7 - Posted 2012-04-20 23:02:30 »

In your client code, you only invoke connect(). Is there more code to this or does the main thread terminate after that?

If the main thread terminates: that is the reason you are seeing "connection reset", because the process ended before it could tell the other side that the TCP connection should terminate.

Offline GabrielBailey74
« Reply #8 - Posted 2012-04-20 23:07:50 »

Whole Client class (Minus the methods for custom System.out.print)

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
   // Main program launch point.
  public static void main(String[] args) {
      new Client();
   }

   // Constructor.
  public Client() {
      connect(port);
   }

   // First method called.
  private void connect(int port2) {
      try {
         socket = new Socket("localhost", port2);
         log(System.out, "Client connected");
         printWriter = new PrintWriter(socket.getOutputStream(), true);
         sendData("Hello Socket");
         sendData("WOOOOOOOOOOOOO");
         closeCons();
      } catch (SocketException e1) {
         log(System.err, "No Available Server launched on port: "+port2);
         System.exit(0);
      } catch (Exception e) {
         log(System.err, e.getMessage());
      }
   }

   // Method used to close connections.
  private void closeCons() {
      try {
         printWriter.close();
         socket.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   // Custom method used to send Data.
  private void sendData(String text) {
      if (printWriter != null) {
         printWriter.println(text);
      } else if (printWriter == null) {
         log(System.err, "PrintWriter == NULL!");
         return;
      }
   }


This is wierd.., why would the console be printing out that a connection from 'activate.adobe.com' was accepted before/instead of my Client?
1  
2  
3  
4  
Server listening on port: 4442...
Connection accepted from: activate.adobe.com
Hello Socket
WOOOOOOOOOOOOO


Used from:
1  
clientSocket.getLocalAddress().getCanonicalHostName()

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #9 - Posted 2012-04-20 23:41:31 »

Oh! You close the connection after you are done with writing stuff into it Tongue

activate.adobe.com resolves to 192.150.16.69, which is somehow your IP? That's weird Grin

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline GabrielBailey74
« Reply #10 - Posted 2012-04-20 23:47:48 »

Could you help me ra4king lol, i've been swapping code, moving it, debugging for a few hours now e.e..

Server steps: launch, connect, receive, loop.
Quote
Server listening on port: 4442...
Connection accepted from: /127.0.0.1
Client Message: Hello Socket.
Client Message: WOOOOOOOOOOOOO.
Client Connected Still: true
Server closed yet: false

Client steps: launch, connect, send.
Quote
Client connected
Message sent: Hello Socket.
Message sent: WOOOOOOOOOOOOO.
Socket Connected Still: true

How can I get the client to constantly remain connected?
About the activate.adobe.com... I swear i'm infected by a virus from trying to download some free 'Photoshop.exe' e.e..

Offline jonjava
« Reply #11 - Posted 2012-04-21 01:07:06 »

Note: I haven't tested the code below.

Also, instead of writing a client to test your server, try to connect to it through telnet or something similar. That's what I do :P

I suggest you read about Sockets and Server/Client communications in general from [size=2pt]google search->[/size] http://www.oracle.com/technetwork/java/socket-140484.html

[size=8pt]
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
class TestServer implements Runnable {
 ServerSocket ss;

  // Constructor
TestServer( int port ) {
  ss = new ServerSocket( port );
  Thread t = new Thread( this );
  t.start();
 }

  @Override
  public void Run() {
     while( true ) {
     Socket socket = ss.accept(); // blocking
    if (socket != null) new TestClient( socket );
     }
   }

  // Test starter
 public static void main(String[]  argv) {
   int port = 8080; // Default port

   if (argv.length > 0) port = Integer.parseInt( argv[1] );

   new TestServer( port );
  }


}


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
class TestClient implements Runnable {
 Socket socket;

  // Constructor
TestClient( Socket socket ) {
 if (socket != null){
   this.socket = socket;
   Thread t = new Thread( this );
   t.start();
  }
 }

  @Override
   public void Run() {
    OutputStream = socket.getOutputStream();
    InputStream = socket.getInputStream();
    byte[] buffer = new byte[512];

    // Before listening for input, send the client a greeting.
   out.write( "Hello".getBytes() );

    while( true ) {
    int bytesRead = in.read( buffer ); // blocks
   if (bytesRead < 0) { // client disconnected
    socket.close();
     break;
     }

    if (bytesRead > 0) { // There's data to be read
     // do somethign with the data inside buffer
     
      // Send data back to client. ( Echo server )
     out.write( buffer );
    }

    }

  }
}
[/size]

Offline GabrielBailey74
« Reply #12 - Posted 2012-04-21 01:11:28 »

Thanks mate, got it all working now.
Think i'll be implementing a GUI of somesort Smiley

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #13 - Posted 2012-04-21 01:51:03 »

It's best to specify a charset, specifically UTF-8, so do getBytes("UTF-8").

Nice that you got it working! Smiley

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

TehJavaDev (16 views)
2014-08-28 18:26:30

CopyableCougar4 (25 views)
2014-08-22 19:31:30

atombrot (38 views)
2014-08-19 09:29:53

Tekkerue (35 views)
2014-08-16 06:45:27

Tekkerue (32 views)
2014-08-16 06:22:17

Tekkerue (20 views)
2014-08-16 06:20:21

Tekkerue (31 views)
2014-08-16 06:12:11

Rayexar (66 views)
2014-08-11 02:49:23

BurntPizza (44 views)
2014-08-09 21:09:32

BurntPizza (34 views)
2014-08-08 02:01:56
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!