import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
public class Server {
static List<DataOutputStream> outs;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(2400);
outs = new LinkedList();
Socket socket;
DataOutputStream out;
while (true) {
socket = serverSocket.accept();
new Broadcaster(new DataInputStream(socket.getInputStream()),
out = new DataOutputStream(socket.getOutputStream())).start();
outs.add(out);
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class Broadcaster extends Thread {
DataInputStream in;
DataOutputStream out;
Broadcaster(DataInputStream in, DataOutputStream out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
while (true) {
try {
String message = in.readUTF();
for (DataOutputStream out : outs) {
if (out != this.out) {
out.writeUTF(message);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 2400);
new Sender(socket).start();
new Receiver(socket).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Sender extends Thread {
Scanner sc;
DataOutputStream out;
Sender(Socket socket) {
try {
this.out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
this.sc = new Scanner(System.in);
}
@Override
public void run() {
while (true) {
try {
this.out.writeUTF(sc.nextLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Receiver extends Thread {
DataInputStream in;
Receiver(Socket socket) {
try {
this.in = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
System.out.println(this.in.readUTF());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
댓글
댓글 쓰기