프로그램 문제

자바 채팅 소스

낙산암 2021. 11. 11. 22:11

============================================서버 쪽===================================
import java.net.;
import java.io.
;
import java.util.Scanner;

public class TcpIpServer5 {
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;

    try {
        // 서버소켓을 생성하여 7777번 포트와 결합(bind)시킨다.
        serverSocket = new ServerSocket(7777);
        System.out.println("서버가 준비되었습니다.");

        socket = serverSocket.accept();

        Sender   sender   = new Sender(socket);
        Receiver receiver = new Receiver(socket);

        sender.start();
        receiver.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
} // main

} // class

class Sender extends Thread {
Socket socket;
DataOutputStream out;
String name;

Sender(Socket socket) {
    this.socket = socket;
    try {
        out = new DataOutputStream(socket.getOutputStream());
        name = "["+socket.getInetAddress()+":"+socket.getPort()+"]";
    } catch(Exception e) {}
}

public void run() {
    Scanner scanner = new Scanner(System.in);
    while(out!=null) {
        try {
            out.writeUTF(name+scanner.nextLine());        
        } catch(IOException e) {}
    }
} // run()

}

class Receiver extends Thread {
Socket socket;
DataInputStream in;

Receiver(Socket socket) {
    this.socket = socket;
    try {
        in = new DataInputStream(socket.getInputStream());
    } catch(IOException e) {}

}

public void run() {
    while(in!=null) {
        try {
            System.out.println(in.readUTF());
        } catch(IOException e) {}
    }
} // run

}

============================================클라이언트쪽================================

public class TcpIpClient5 {
public static void main(String args[]) {
try {
String serverIp = "127.0.0.1";

        // 소켓을 생성하여 연결을 요청한다.
        Socket socket = new Socket(serverIp, 7777); 

        System.out.println("서버에 연결되었습니다.");
        Sender sender = new Sender(socket);
        Receiver receiver = new Receiver(socket);

        sender.start();
        receiver.start();
    } catch(ConnectException ce) {
        ce.printStackTrace();
    } catch(IOException ie) {  
        ie.printStackTrace();
    } catch(Exception e) {
        e.printStackTrace();  
    }  
} // main

} // class