Results 1 to 6 of 6
Thread: Java Server Socket Problem...
- 12-30-2011, 06:56 AM #1
Member
- Join Date
- Jun 2011
- Posts
- 21
- Rep Power
- 0
Java Server Socket Problem...
Okay so I have been trying to make a 2D Java Game.It is intended for a MMORPG game. However my Server and client hook seem to fail a lot. It runs basicly by the client sending a Short to the server as a request. This request tells what the Server to respond to. My coding is very messy I know that I would like some input to where the hook fails or how the request could better be sent.
Here is my Server Main Class File:
Here is My Server Thread:Java Code:package org; //Server.java import java.net.*; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import org.connection.Mysql; public class Server { private ServerSocket ss; public static Socket socket; Map<Socket,DataOutputStream> map=new HashMap<Socket,DataOutputStream>(); DataOutputStream dout; Mysql conn; public static String getTime() { SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss"); Date now = new Date(); String strDate = sdfDate.format(now); return strDate; } public static void main(String[] args) throws ParseException { try { int port=9999; new Server(port); } catch(NumberFormatException nfe) { nfe.printStackTrace(); System.out.println("Usage:> java Server <portno(int)>"); return; } catch(ArrayIndexOutOfBoundsException aioobe) { aioobe.printStackTrace(); System.out.println("Usage:> java Server <portno(int)>"); return; } } public Server(int port) { listen(port); } private void listen(int port) { try { System.out.println("Forgotten Legend is now Online! [" + getTime() + "]"); conn = new Mysql(); while(true) { ss=new ServerSocket(port); socket=ss.accept(); new ServerThread(this, socket); dout=new DataOutputStream(socket.getOutputStream()); map.put(socket, dout); } } catch (IOException e) { e.printStackTrace(); } } public void sendToAll(String message,Socket cur_soc) { synchronized(map){ Set<Socket> socket_set=map.keySet(); Iterator<Socket> itr=socket_set.iterator(); while(itr.hasNext()) { try{ Socket s=itr.next(); if(s != cur_soc) { DataOutputStream dout = map.get(s); dout.writeUTF(message); } } catch(IOException ioe){ } } } } void send(int s, int m, int x, int y) throws Exception { dout.writeInt(s); dout.writeInt(m); dout.writeInt(x); dout.writeInt(y); } public void removeConnection(Socket soc) { synchronized(map) { map.remove(soc); try { soc.close(); } catch(IOException e) { } } } }
Here is My Client to check for requests and send back requests:Java Code:package org; //ServerThread.java import java.net.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.io.*; public class ServerThread extends Thread{ private Server server; private Socket socket; public static String username; public static String password; public static short request = 0; // default for none public static boolean failed = true; public ServerThread(Server server,Socket socket) { this.server=server; this.socket=socket; start(); } public void run() { try { DataInputStream din = new DataInputStream(socket.getInputStream()); while(true) { request = din.readShort(); if (request == 300) { String output = din.readUTF(); System.out.println("Connected: " + output); username = output.substring(0, output.indexOf(",")); password = output.substring(output.indexOf(",") + 1).trim(); try { server.conn.login(username, password); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } else if (request == 100) { String message = din.readUTF(); din.readShort(); server.sendToAll(message,socket); System.out.println(message + " [" + Server.getTime() + "]"); } else if (request == 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } catch(EOFException eof){ eof.printStackTrace(); } catch(IOException ioe){ ioe.printStackTrace(); } } private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while(two_halfs++ < 1); } return buf.toString(); } public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } }
Any help would be loved :)Java Code:package org.connect; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JOptionPane; import org.Board; import org.Main; import org.Player; import org.tools.Tools; public class Server implements Runnable { private Socket socket = new Socket(); private InetSocketAddress addr; public static DataInputStream din; private static DataOutputStream dout; Board board; public static short loginRequest = 0; // 0 returns as waiting public short checker; @Override public void run() { try { while(true) { String msg=din.readUTF(); if (!msg.isEmpty()) { Board.addChat(msg); } if (Board.login == false) { checker = din.readShort(); if (checker == 300) { Main.failed = false; } else { Main.failed = true; } } } } catch (IOException e) { Tools.log(e); } } public Server() throws IOException { try { addr=new InetSocketAddress(InetAddress.getLocalHost().getHostName(), 9999); socket.connect(addr); String username = Board.usernameBox.getText(); String password = Board.passwordBox.getPass(); din = new DataInputStream(socket.getInputStream()); dout = new DataOutputStream(socket.getOutputStream()); if (loginRequest == 300) { dout.writeShort(300); dout.writeUTF(username + "," + password); } if (din.readShort() == 400) { new Thread(Server.this).start(); System.out.println("Server connected"); Board.login = true; } else { Main.failed = true; } } catch(UnknownHostException uhe) { JOptionPane.showMessageDialog(null, "Server offline","The Forgotten Legend - Error",JOptionPane.INFORMATION_MESSAGE); return; } catch(IOException ioe) { JOptionPane.showMessageDialog(null,"Connection refused","The Forgotten Legend - Error",JOptionPane.INFORMATION_MESSAGE); return; } } public static void write() throws IOException, InterruptedException { dout.writeShort(100); String msg = Board.message.trim(); dout.writeUTF(Player.getUsername() + ": " + msg); Board.addChat(Player.getUsername() + ": " + msg); Board.textBox.setText(""); } public static void updatePlayers() { } }
- 12-30-2011, 01:32 PM #2
Re: Java Server Socket Problem...
What's a hook? How does a hook fail?I would like some input to where the hook fails or how the request could better be sent.
Can you explain how the code currently works and what is wrong with that. Perhaps post some sample input and output and some debug track that shows the problem
The posted code does not compile"
You posted 2 copies of Server and no Client.
There are many missing classes.Last edited by Norm; 12-30-2011 at 01:39 PM.
- 12-30-2011, 04:59 PM #3
Member
- Join Date
- Jun 2011
- Posts
- 21
- Rep Power
- 0
Re: Java Server Socket Problem...
No the two server class are the server client. First one is Server second one is Client. And an example would be a person enters there username and password it goes to my MYSQL find and return if the statement is true or false. If true then the person is logged in. If false then it show invalid username or password on the client. However it only works on one client and the other clients it throws a bunch of MYSQL errors. Here is my MYSQL class if it helps you at all.
[CODE]
package org.connection;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.Server;
public class Mysql {
static Connection connection = null;
String url = "mysite URL...to database";
String username = "My username...to database";
String password = "My password...to database";
String driverName = "org.gjt.mm.mysql.Driver";
public static boolean failed = false;
public static short work = 0;
public static boolean connected = false;
static int id;
static String user;
static String pass;
static String email;
static int rank;
static int attXP;
static int powerXP;
static int defXP;
static int attLVL;
static int powerLVL;
static int defLVL;
static int locX;
static int locY;
static int map;
public Mysql() {
try {
Class.forName(driverName);
connection = DriverManager.getConnection(url, username, password);
System.out.println("MYSQL up and running..." + " [" + Server.getTime() + "]");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void login(String username, String password) throws SQLException, NoSuchAlgorithmException, IOException {
DataOutputStream dout = new DataOutputStream(Server.socket.getOutputStream());
String unhidePassword = SHA1(password);
// Execute the query
ResultSet rs = connection.prepareStatement("select id from player where username = '" + username + "'and password = '" + unhidePassword + "';" ).executeQuery();
// Loop through the result set
if (!rs.next() && rs.getRow() == 0) {
failed = true;
work = 500;
} else {
failed = false;
work = 400;
}
dout.writeShort(work);
if (work == 400) {
connected = true;
}
dout.writeShort(0);
}
public static void loadPlayer(String username) {
try {
PreparedStatement pstat = connection.prepareStatement("select * from player where username = '" + username + "';");
ResultSet rs = pstat.executeQuery();
while (rs.next()) {
id = rs.getInt(1); // 1st column in query
user = rs.getString(2); // 2nd column in query
pass = rs.getString(3); // ect...
email = rs.getString(4);
rank = rs.getInt(5);
attXP = rs.getInt(6);
powerXP = rs.getInt(7);
defXP = rs.getInt(8);
attLVL = rs.getInt(9);
powerLVL = rs.getInt(10);
defLVL = rs.getInt(11);
locX = rs.getInt(12);
locY = rs.getInt(13);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static int getID() {
return id;
}
public static String getUsername() {
return user;
}
public static String getEmail() {
return email;
}
public static int getRank() {
return rank;
}
public static int getAttackXP() {
return attXP;
}
public static int getPowerXP() {
return powerXP;
}
public static int getDefenseXP() {
return defXP;
}
public static int getAttackLevel() {
return attLVL;
}
public static int getPowerLevel() {
return powerLVL;
}
public static int getDefenseLevel() {
return defLVL;
}
public void savePlayer(String username ) {
try {
PreparedStatement pstat = connection.prepareStatement("UPDATE " + username + "Set attackXP = 30 WHERE attackXP=");
ResultSet rs = pstat.executeQuery();
System.out.println("Saving was succeful!");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void destoryConn() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
}
}
[\CODE]
- 12-30-2011, 05:04 PM #4
Re: Java Server Socket Problem...
Sorry, I don't know anything about MYSQL.it only works on one client and the other clients it throws a bunch of MYSQL errors.
For testing, can you remove the MYSQL code and have a simple arraylist for user lookup?
- 12-30-2011, 05:12 PM #5
Member
- Join Date
- Jun 2011
- Posts
- 21
- Rep Power
- 0
Re: Java Server Socket Problem...
What do you mean? Just remove all the MYSQL connection and then hard codding the username and password?
- 12-30-2011, 05:13 PM #6
Similar Threads
-
Problem reading from server socket
By glauber in forum Advanced JavaReplies: 5Last Post: 02-17-2011, 12:11 PM -
Java Socket server with C client problem
By rnvrnv in forum NetworkingReplies: 6Last Post: 11-09-2010, 12:47 AM -
Simple Socket program: Java Client- C server
By pimmling in forum New To JavaReplies: 1Last Post: 11-08-2010, 01:27 PM -
Problem on server side (Socket Programming)
By ersachinjain in forum NetworkingReplies: 9Last Post: 05-06-2010, 04:21 PM -
Client Server socket problem - help needed
By kellaw in forum Threads and SynchronizationReplies: 6Last Post: 10-03-2008, 06:49 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks