Receiver
package kr.or.didt.tcp;
import java.io.DataInputStream;
import java.net.Socket;
// 이 클래스는 Socket을 통해서 메시지를 받아서 화면에 출력하는 역할을 담당하는 클래스이다.
public class Receiver extends Thread {
private Socket socket;
private DataInputStream dis;
//생성자
public Receiver(Socket socket){
this.socket = socket;
try {
dis = new DataInputStream(socket.getInputStream());
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
public void run() {
while(dis != null){
try {
System.out.println(dis.readUTF());
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
Sender
package kr.or.didt.tcp;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
//이 클래스는 Socket을 통해서 메시지를 보내는 역할만 담당하는 클래스이다.
public class Sender extends Thread{
private Socket socket;
private DataOutputStream dos;
private String name;
private Scanner scan;
// 생성자
public Sender(Socket socket) {
this.socket = socket;
scan = new Scanner(System.in);
System.out.print("이름 입력: ");
name = scan.nextLine();
try {
dos = new DataOutputStream(socket.getOutputStream());
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
public void run() {
while(dos != null){
try {
dos.writeUTF(name + " : " + scan.nextLine());
} catch (Exception e) {
// TODO: handle exception
}
}
}
}