Skip to content

Instantly share code, notes, and snippets.

@Danny02
Last active December 20, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danny02/6100525 to your computer and use it in GitHub Desktop.
Save Danny02/6100525 to your computer and use it in GitHub Desktop.
some old little IRC client
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package communication;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author rEaCH
*/
public class IRCClient {
private final BufferedWriter out;
private final BufferedReader in;
private String channel, host;
private final Socket server;
public IRCClient(String host, int port) {
this.host = host;
try {
server = new Socket(host, port);
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
try {
out = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
in = new BufferedReader(new InputStreamReader(server.getInputStream()));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void connect(String myNick) {
try {
writeMsg("USER", myNick + " host irc " + myNick);
writeMsg("NICK", myNick);
String line;
while ((line = in.readLine()) != null) {
if (line.indexOf("004") >= 0) {
break;
}
parsePing(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void disconnect() {
try {
server.close();
} catch (IOException ex) {
}
}
private void writeMsg(String cmd, String msg) {
writeIrc(cmd + " " + msg + "\r\n");
}
public void joinChannel(String channel) {
String this.channel = channel;
writeMsg("JOIN", channel + " blubber");
}
public void sendPong() {
writeIrc("PONG " + host);
}
private void writeIrc(String msg) {
try {
out.write(msg);
out.flush();
} catch (IOException ex) {
}
}
public void writePrivMsg(String msg) {
writeMsg("PRIVMSG " + channel, ":" + msg);
}
public String recvMsg() throws IOException {
String line = in.readLine();
if (line != null) {
parsePing(line);
} else {
line = "";
}
return line;
}
private void parsePing(String line) {
if (line.startsWith("PING ")) {
writeMsg("PONG", line.substring(6));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment