-
Interchat System
THIS WAS MADE BY SLYSOFT POSTING ON BEHALF OF HIM
Estimated time:
20min
Difficulty:
7
Anti leech?
Only if you are a total noob on Java :)
Description
Chat between servers
Preparation
Create a folder where you put seperate server files
-----------------------------------------------------------------
1: InterChat part - chat server
Save following files to folder, and compile them.
ICServer.java:
Code:
import java.io.*;
import java.net.*;
public class ICServer {
public static int runPort = 54551;
public static void println(String x) {
System.out.println(x);
}
public static ICConfigHandler icg;
public static void main(String[] args) throws Exception {
println("Slysoft's InterChat Server v0.1");
println("Starting up, please standby..");
println(" ");
icg = new ICConfigHandler();
try {
ServerSocket ss = new ServerSocket(runPort);
println("Started! Listening on port " + runPort);
while (true) {
try {
Socket s = ss.accept();
String connectingHost = s.getInetAddress().getHostName();
println("Connection accepted from: " + connectingHost);
if (icg.getOnDb("IPBan", connectingHost)) {
println(connectingHost + ": Connection denied, ipban!");
s.close();
} else {
new Thread(new ICThread(s)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
println("Socket error! Exception trace coming..");
e.printStackTrace();
}
println(" ");
println("* Program closing *");
}
}
ICConfigHandler.java:
Code:
import java.io.*;
public class ICConfigHandler {
public ICConfigHandler() {
log("Loading config.");
boolean OK = loadConfig();
if (!OK) {
log("ERROR: Failled loading config.");
System.exit(1);
}
log("Done.");
}
public static int cfgMaxC = 100;
public static String[] cfName = new String[cfgMaxC];
public static String[] cfVal = new String[cfgMaxC];
public static int cfgCount = 0;
public static void log(String s) {
System.out.println("[CONFIG] " + s);
}
public static String getCfg(String name) {
for (int i = 0; i < cfgCount; i++) {
if (cfName[i].equals(name)) {
return cfVal[i];
}
}
return "";
}
public static boolean getOnDb(String name, String val) {
for (int i = 0; i < cfgCount; i++) {
if (cfName[i].equals(name) && cfVal[i].equals(val)) {
return true;
}
}
return false;
}
public static void addConfig(String name, String val) {
if (cfgCount >= cfgMaxC) {
log(
"WARNING: Config name " + name
+ " skipped because of out of space");
return;
}
cfName[cfgCount] = name;
cfVal[cfgCount] = val;
cfgCount++;
}
public static boolean loadConfig() {
try {
BufferedReader in = new BufferedReader(new FileReader("config.cfg"));
String data = null;
while ((data = in.readLine()) != null) {
if (!data.startsWith("#")) {
String[] cx = data.split("::");
if (cx.length >= 2) {
addConfig(cx[0], cx[1]);
log("Config loaded: " + cx[0] + "::" + cx[1]);
}
}
}
return true;
} catch (Exception e) {}
return false;
}
}
ICThread.java:
Code:
import java.io.*;
import java.net.*;
import java.util.Vector;
public class ICThread implements Runnable {
static Vector cHandlers = new Vector(3);
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String conHost;
public ICThread(Socket ss) throws Exception {
this.socket = ss;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
conHost = socket.getInetAddress().getHostName();
}
public synchronized void printOut(String s) {
out.println(s);
out.flush();
}
public void printOutAll(String s) {
for (int i = 0; i < cHandlers.size(); i++) {
ICThread cHandler = (ICThread) cHandlers.elementAt(i);
cHandler.printOut(s);
}
}
public String readIn() throws Exception {
String streamLine;
while ((streamLine = in.readLine()) != null) {
return streamLine;
}
return "QUIT";
}
public void processChat() throws Exception {
String streamLine;
String[] streamSplit;
while (!(streamLine = readIn()).equals("QUIT")) {
ICServer.println("[" + conHost + "]: " + streamLine);
streamSplit = streamLine.split(" ");
if (streamSplit[0].equals("WELCOME")) {
String userName = streamSplit[1].replaceAll("!", " ");
printOutAll(
"SMSG-" + streamSplit[2] + " Welcome " + userName
+ " to " + streamSplit[2] + " on "
+ ICServer.icg.getCfg("serverName") + " chat network!");
}
if (streamSplit[0].equals("CHAT")) {
String userName = streamSplit[1].replaceAll("!", " ");
String chatString = streamSplit[3].replaceAll("/", " ");
printOutAll(
"SMSG-" + streamSplit[2] + " " + userName + ": "
+ chatString);
}
if (streamSplit[0].equals("GLOBALCHAT")) {
String userName = streamSplit[1].replaceAll("!", " ");
String chatString = streamSplit[2].replaceAll("/", " ");
printOutAll("SMGLOBAL [GLOBAL] " + userName + ": " + chatString);
}
}
}
public void run() {
try {
cHandlers.addElement(this);
processChat();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
in.close();
out.close();
} catch (Exception x) {} finally {
cHandlers.removeElement(this);
}
}
}
}
config.cfg (Config file):
Code:
#Put server name here!
serverName::IC
#Example ipban field!
IPBan:1.2.3.4
Now youve got a chat server.. next the part to be attached into server.
2. Server part - chat client
Copy following into file IChatClient.java
Code:
import java.io.*;
import java.net.*;
public class IChatClient implements Runnable {
public static Socket cSock;
public static BufferedReader in;
public static PrintWriter out;
public static String serverConnect = "";
public static boolean tryConnect = false;
public static boolean autoRetry = false;
public static boolean isConnected = false;
public static boolean closeConnection = false;
public static void println(String s) {
System.out.println("[InterChat] " + s);
}
public IChatClient(String connectTo) {
println("Starting InterChat client, (C) Slysoft");
serverConnect = connectTo;
tryConnect = true;
}
public void run() {
while (true) {
run2(); // Infinite loop for keeping connection alive!
}
}
public void tryConnection() throws Exception {
cSock = new Socket(serverConnect, 54551);
in = new BufferedReader(new InputStreamReader(cSock.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(cSock.getOutputStream()));
}
public String readIn() throws Exception {
if (closeConnection) return "QUIT";
String streamLine;
while ((streamLine = in.readLine()) != null) {
return streamLine;
}
return "QUIT";
}
public void printOut(String s) {
if (isConnected) {
out.println(s);
out.flush();
}
}
public void sendPlayerStuff(String globMessage, String channel) {
int msgTo = 1;
do {
if (server.playerHandler.players[msgTo] != null) {
if (server.playerHandler.players[msgTo].onChannel.equals(channel)) {
server.playerHandler.players[msgTo].globalMessage = "[InterChat] "
+ globMessage;
}
}
msgTo++;
} while (msgTo < server.playerHandler.maxPlayers);
}
public void sendChatMessage(String userName, String channel, String message) {
String propUser = userName.replaceAll(" ", "!");
String propMessage = message.replaceAll(" ", "/");
printOut("CHAT " + propUser + " " + channel + " " + message);
}
public void sendGlobalChatMessage(String userName, String message) {
String propUser = userName.replaceAll(" ", "!");
String propMessage = message.replaceAll(" ", "/");
printOut("GLOBALCHAT " + propUser + " " + message);
}
public void sendWelcomeMessage(String userName, String channel) {
String propUser = userName.replaceAll(" ", "!");
printOut("WELCOME " + propUser + " " + channel);
}
public void doChatStuff() throws Exception {
println("Starting chat processing..");
while (true) {
String sentSS = readIn();
println(sentSS);
if (sentSS.equals("QUIT")) {
return;
}
if (sentSS.startsWith("SMGLOBAL")) {
String dx = sentSS.substring(9);
server.playerHandler.messageToAll = "[InterChat] " + dx;
}
if (sentSS.startsWith("SMSG-")) {
String[] smArray1 = sentSS.split(" ");
String[] smArray2 = smArray1[0].split("-");
String channel = smArray2[1];
String message = sentSS.substring(smArray1[0].length() + 1);
sendPlayerStuff(message, channel);
}
}
}
public void run2() {
while (!tryConnect) {
if (autoRetry) {
tryConnect = true;
}
}
try {
println("Connecting to: " + serverConnect);
tryConnection();
isConnected = true;
tryConnect = false;
closeConnection = false;
println("Connection successfull!");
doChatStuff();
} catch (Exception e) {
println("Unable to connect: " + serverConnect);
} finally {
try {
cSock.close();
in.close();
out.close();
} catch (Exception e) {}
isConnected = false;
tryConnect = false;
closeConnection = false;
println("Connection closed");
}
}
}
Then add this to server.java under
Code:
"public static PlayerHandler playerHandler = null"
Code:
public static IChatClient icc = null;
and this under
Code:
"playerHandler = new PlayerHandler();"
Code:
String icServer = "127.0.0.1"; //Server to connect
icc = new IChatClient(icServer);
icc.autoRetry = true; //Auto retry on failure
(new Thread(icc)).start();
This to player.java
Code:
public String onChannel = "#InterChat";
And this to client.java
Code:
if (command.startsWith("ichat-glob") && playerRights >= 2) { //GLOBAL MESSAGES
try {
String gmsg = command.substring(11);
server.icc.sendGlobalChatMessage(playerName, gmsg);
} catch (Exception e) { sendMessage("Invalid syntax");}
}
if (command.startsWith("ichat-channel")) { //CHANNEL
try {
String gchn = command.substring(14);
if (!gchn.startsWith("#") && playerRights < 2) {
sendMessage("Sorry, only admins can use channel names with no # on beginning!");
} else {
onChannel = gchn;
server.icc.sendWelcomeMessage(playerName, onChannel);
}
} catch (Exception e) { sendMessage("Invalid syntax");}
}
if (command.startsWith("iyell")) { //TALK
try {
String gmsg = command.substring(6);
server.icc.sendChatMessage(playerName, onChannel, gmsg);
} catch (Exception e) { sendMessage("Invalid syntax");}
}
if (command.startsWith("ichat-connect") && playerRights >= 2) {
sendMessage("Connection attempt will automatically result when not connected");
server.icc.tryConnect = true;
}
if (command.startsWith("ichat-disconnect") && playerRights >= 2) {
sendMessage("Connection will be disconnected.");
server.icc.closeConnection = false;
}
if (command.startsWith("ichat-autoretryon") && playerRights >= 2) {
sendMessage("Connecting will be automatically retried after lost connection");
server.icc.autoRetry = true;
}
if (command.startsWith("ichat-autoretryoff") && playerRights >= 2) {
sendMessage("Connecting will be no longer automatically retried after lost connection");
server.icc.autoRetry = false;
}
And this under welcome message code
Code:
server.icc.sendWelcomeMessage(playerName, onChannel);
Remember to start IC server also when starting your server, or chat system will NOT work! It also will not lag your server badly, as it runs on seperate thread, and it will not wait on IC client
THIS WAS MADE BY SLYSOFT! POSTING ON HIS BEHALF
-
nicely done sarah/sly its awsome.
-
Whats this: [Only registered and activated users can see links. Click Here To Register...]
LOL :d
-
-
Very very nice, good job you two. :)
-
-
Don't post other's work. His is already here..