Skip to content

Instantly share code, notes, and snippets.

@moomoohk
Created April 30, 2013 01:26
Show Gist options
  • Save moomoohk/5486070 to your computer and use it in GitHub Desktop.
Save moomoohk/5486070 to your computer and use it in GitHub Desktop.
package networking;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import networking.Utils.Operations;
import networking.commands.client.SendMessageCommand;
import com.moomoohk.MooCommands.Command;
import com.moomoohk.MooConsole.Console;
public class Client implements Runnable
{
private int port;
private String server, name;
private Thread listenerThread;
private Socket socket;
private OutputStream outputStream;
private ObjectOutputStream objectOut;
private ObjectInputStream objectIn;
private boolean connected = false;
public static Console console;
public static void main(String[] args)
{
console = new Console();
buildGUI();
}
public static void buildGUI()
{
final JFrame f = new JFrame("Setup\n");
f.setLayout(null);
f.setSize(200, 160);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel nameLabel = new JLabel("Name:\n");
final JTextField name = new JTextField();
JLabel ipLabel = new JLabel("IP:\n");
final JTextField ip = new JTextField();
JLabel portLabel = new JLabel("Port:\n");
final JTextField port = new JTextField("1024\n");
final JButton done = new JButton("Done\n");
nameLabel.setBounds(10, 10, 90, 30);
name.setBounds(60, 10, 130, 30);
ipLabel.setBounds(10, 40, 50, 30);
ip.setBounds(60, 40, 130, 30);
portLabel.setBounds(10, 70, 50, 30);
port.setBounds(60, 70, 130, 30);
done.setBounds(60, 100, 80, 30);
done.setEnabled(false);
done.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent paramActionEvent)
{
f.setVisible(false);
console.setVisible(true);
console.setConsoleTextColor(Color.white);
final Client client = new Client(ip.getText(), Integer.parseInt(port.getText().trim()), name.getText());
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
{
@Override
public void run()
{
client.stop();
}
}));
ArrayList<Command<?>> commands = new ArrayList<Command<?>>();
commands.add(new SendMessageCommand(client, "send", "Sends a String.", 1, -1));
console.loadCommands(commands);
client.start();
}
});
KeyListener fieldListener = new KeyAdapter()
{
@Override
public void keyReleased(KeyEvent paramKeyEvent)
{
if (name.getText().trim().length() != 0 && ip.getText().trim().length() != 0 && port.getText().trim().length() != 0)
done.setEnabled(true);
if (paramKeyEvent.getKeyCode() == 10)
done.doClick();
if (paramKeyEvent.getKeyCode() == 27)
((JTextField) paramKeyEvent.getSource()).setText("\n");
}
};
name.addKeyListener(fieldListener);
ip.addKeyListener(fieldListener);
port.addKeyListener(fieldListener);
f.add(nameLabel);
f.add(name);
f.add(ipLabel);
f.add(ip);
f.add(portLabel);
f.add(port);
f.add(done);
f.setVisible(true);
}
public Client(String server, int port, String name)
{
this.server = server;
this.port = port;
this.name = name;
}
public void start()
{
this.listenerThread = new Thread(this);
this.listenerThread.start();
}
public void stop()
{
if (!connected)
return;
send(Operations.DISCONNECT);
this.listenerThread.interrupt();
}
public void send(Object obj)
{
if (connected)
{
try
{
objectOut.writeUnshared(obj);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
@Override
public void run()
{
try
{
console.addText("Trying to connect...\n");
socket = new Socket(InetAddress.getByName(server), port);
console.addText("Connected.\n");
new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputStream = socket.getOutputStream();
objectOut = new ObjectOutputStream(outputStream);
objectIn = new ObjectInputStream(socket.getInputStream());
connected = true;
console.addText("Sending client name...\n");
send(name);
console.addText("Done.\n");
objectOut.flush();
while (!socket.isClosed())
{
Object obj = objectIn.readObject();
if (obj instanceof String)
console.addText(obj.toString());
else
console.addText("Server sent a " + obj.getClass().toString() + " object.");
}
}
catch (EOFException e)
{
console.addText("Server shut down.\n");
connected = false;
stop();
}
catch (IOException e)
{
console.addText("Failure to read object.\n");
console.addText(e.getClass().getName() + ": " + e.getMessage() + "\n");
for (StackTraceElement ste : e.getStackTrace())
console.addText(ste.toString() + "\n");
}
catch (ClassNotFoundException e)
{
console.addText("Class not found.\n");
}
}
}
package networking;
import java.awt.Color;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import networking.Utils.Operations;
import networking.commands.server.StopServerCommand;
import com.moomoohk.MooCommands.Command;
import com.moomoohk.MooConsole.Console;
public class Server implements Runnable
{
private Thread listenerThread;
private int port;
private boolean running = false;
private ArrayList<SocketThread> connections;
public static Console console;
public static Server server;
public static void main(String[] args)
{
console = new Console();
console.setVisible(true);
ArrayList<Command<?>> commands = new ArrayList<Command<?>>();
commands.add(new StopServerCommand(server, "stop", "Stops the server.", 0, 0));
console.loadCommands(commands);
console.setConsoleTextColor(Color.white);
server = new Server();
server.start();
}
public Server()
{
this.listenerThread = new Thread(this);
connections = new ArrayList<SocketThread>();
}
public void start()
{
this.listenerThread.start();
}
public void stop()
{
running = false;
sendAll(Operations.DISCONNECT);
this.listenerThread.interrupt();
console.addText("Server stopped.\n");
}
@Override
public void run()
{
running = true;
try
{
ServerSocket s = new ServerSocket(63370);
this.port=s.getLocalPort();
console.addText("Server started on port "+this.port+".\n");
console.addText("-\n");
while (running)
{
Socket incoming = s.accept();
ObjectInputStream objectIn=new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream objectOut=new ObjectOutputStream(incoming.getOutputStream());
objectOut.flush();
try
{
String name=(String)(objectIn.readObject());
console.addText(name+" connected.\n");
console.addText("Client info: Canonical host name: "+incoming.getInetAddress().getCanonicalHostName()+", host address: "+incoming.getInetAddress().getHostAddress()+", host name: "+incoming.getInetAddress().getHostName()+"\n");
sendAll(name+" connected.");
connections.add(new SocketThread(incoming, name, this, objectIn, objectOut));
new Thread(connections.get(connections.size()-1)).start();
}
catch(Exception e)
{
console.addText("Client tried to connect but there was an error.\n");
}
}
}
catch (Exception e)
{
console.addText("Error: " + e);
e.printStackTrace();
}
}
public boolean isRunning()
{
return running;
}
public void sendAll(Object obj)
{
for(SocketThread socket:connections)
socket.send(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment