Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.net.ServerSocket;
- import java.util.ArrayList;
- public class Main {
- private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
- public void startReceivingConnections() {
- final ServerSocket server;
- try {
- server = new ServerSocket(1234);
- /* create a thread that will constantly wait for new connections
- * then add them to the list, alerting all other connected hosts
- */
- new Thread(new Runnable() {
- public void run() {
- while (true) {
- Socket s;
- try {
- s = server.accept();
- writeToAll("New connection!");
- managers.add(new SocketManager(s));
- } catch (IOException e) {
- //handle
- }
- }
- }
- }).start();
- } catch (IOException e) {
- //handle
- }
- }
- public void writeToAll(String message) throws IOException {
- for (SocketManager m : managers) {
- m.write(message);
- }
- }
- public static void main(String[] args) {
- Main m = new Main();
- m.startReceivingConnections();
- }
- }
- class SocketManager {
- private Socket socket;
- private DataInputStream inputStream;
- private DataOutputStream outputStream;
- private Thread readThread;
- private boolean shouldCancel = false;
- public SocketManager(Socket s) throws IOException {
- socket = s;
- inputStream = new DataInputStream(s.getInputStream());
- outputStream = new DataOutputStream(s.getOutputStream());
- //putting the read on a separate thread allows us to write at any time
- readThread = new Thread(new Runnable() {
- public void run() {
- while (!shouldCancel) {
- try {
- String line = inputStream.readUTF();
- System.out.println(line);
- } catch (IOException e) {
- //handle exception
- }
- }
- }
- });
- readThread.start();
- }
- public void write(String s) {
- try {
- outputStream.writeUTF(s);
- } catch (IOException e) {
- //handle
- }
- }
- public void cancel() {
- try {
- shouldCancel = true; //do this instead of calling the deprecated readThread.stop()
- socket.close();
- } catch (IOException e) {
- //handle
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement