dcsimg
How to do the connection in J2SE??
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Adeline_Neo
Posted On:   Sunday, February 23, 2003 06:02 AM

I am doing a 2 players game(battle game) using J2me. But i need a server to connect this 2 players to play. I am using J2SE server (server socket connection).

Below is part of the source code for my game server. How or what commands to add in order to let check that:



1) when only 2 players are connected, then the server allow them to connect and play together.


2) If only 1 player connect to the server, then the server does not allow the player to play, and return a message saying, " Waiting for other opponent to connect"

Re: How to do the connection in J2SE??

Posted By:   Adeline_Neo  
Posted On:   Sunday, February 23, 2003 06:05 AM

Below is the soucecode of my server, pls help me to modify it. Thanks


import java.io.*;
import java.net.*;


public class ChatServer {

int current = 0;
String [] lines = new String [256];
ServerSocket serverSocket;

public ChatServer (int port) throws IOException {
serverSocket = new ServerSocket (port);
System.out.println ("Serving port: "+port);
}


public void run () {
while (true) {
try {
Socket socket = serverSocket.accept ();
handleRequest (new BufferedReader
(new InputStreamReader (socket.getInputStream ())),
new OutputStreamWriter (socket.getOutputStream ()));
socket.close ();
}
catch (Exception e) {
e.printStackTrace (System.err);
}
}
}



public void handleRequest (BufferedReader reader,
Writer writer) throws IOException {

// analyze request line

String request = reader.readLine ();
System.out.println ("handling: "+request);
int s0 = request.indexOf (' ');
int s1 = request.indexOf (' ', s0+1);

String method = request.substring (0, s0);
String address = request.substring (s0+1, s1);

// determine first line

int start = current - 20; // default;
int cut = address.indexOf ("?start=");

if (cut != -1)
start = Integer.parseInt (address.substring (cut+7));


// skip headers

while (true) {
String s = reader.readLine ();
System.out.println ("header: "+s);
if (s == null || s.length () == 0) break;
}

// in case of post, store given string

if (method.equalsIgnoreCase ("post")) {

String nick = reader.readLine ().substring (5);
String text = reader.readLine ().substring (5);
String score = reader.readLine ().substring (6);


try {
int i = Integer.parseInt(score.trim());
int entry = Integer.parseInt(text.trim());
System.out.println("int i = " + i);

if (entry == 1)
{
int newScore = i - 10;
String Nscore = Integer.toString(newScore);
String msg = "Fiercely attacks its opponent!";
System.out.println ("score="+Nscore);
lines [(current++) % lines.length] = nick + " " + msg + "Score: " +Nscore;
}
About | Sitemap | Contact