Socket 으로 채팅 구현
다대다 채팅 기능 구현중. 완성하면 업데이트 예정
업데이트 : 멀티 채팅 구현 :
https://moluuuuuuuu.blogspot.com/2023/03/blog-post.html
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss;
Socket s;
DataInputStream in;
DataOutputStream out;
ss = new ServerSocket(2400);
s = ss.accept();
new Sender(s).start();
new Receiver(s).start();
}
}
class Sender extends Thread {
Socket s;
DataOutputStream out;
BufferedReader in;
Sender(Socket sk) {
s = sk;
try { out = new DataOutputStream(s.getOutputStream()); } catch (Exception e) {}
in = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
while (true)
try { out.writeUTF(in.readLine()); } catch (Exception e) {}
}
}
class Receiver extends Thread {
Socket s;
DataInputStream in;
Receiver(Socket sk) {
s = sk;
try { in = new DataInputStream(s.getInputStream()); } catch (Exception e) {}
}
@Override
public void run() {
while (true)
try { System.out.println(in.readUTF()); } catch (Exception e) {}
}
}
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 2400);
new Sender(s).start();
new Receiver(s).start();
}
}
댓글
댓글 쓰기