Programming/Java
Day 26(9/7) TcpipClient
juyinjang25
2016. 9. 8. 18:19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; //ClientSender, Receiver는 각각 Thread 상속하며 run()을 재정의 //Thread로 start()하면 run()이 실행됨 //socket을 생성하여 접속 위치를 설정 //sender, receiver로 각각 socket 생성해서 run() //Sender 정리 //Sender에서 필요한 자원:내 이름(겐지), DataOutputStream(바이트 데이터 보내는 운송로) //운송로 생성 후에 socket에 붙인다. //run()으로 데이터스트림이 생기면, 저장돼있던 name을 써서 보내도록(writeUTF로) //데이터스트림 있는 한, 입력한 것 써서 보내도록 class ClientSender extends Thread { String name; DataOutputStream dos; // 스트림의 정보가 저장되는 변수 public ClientSender(Socket socket, String name) {// 어디에서 뭘 받아오는지 this.name = name; try { dos = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { Scanner sc = new Scanner(System.in); try { if (dos != null) { dos.writeUTF(name); } while (dos != null) { dos.writeUTF(sc.nextLine()); } } catch (IOException e) { e.printStackTrace(); } } } // Receiver 정리 // 필요 자원:상대방 이름(한민수), 들여오는 Stream 필요 // 운송로 만들어서 소켓에 붙여줌 // run()은 데이터스트림 있는 한 읽어 온 것을 출력해줌 class ClientReceiver extends Thread { String name; DataInputStream dis; public ClientReceiver(Socket socket) { try { dis = new DataInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } public void run() { while (dis != null) { try { System.out.println(dis.readUTF()); } catch (IOException e) { e.printStackTrace(); } } } } public class TcpIpClient { public static void main(String[] args) { Socket socket; try { socket = new Socket("192.168.0.33", 5000); System.out.println("한민수 컴퓨터에 접속되었습니다."); new ClientSender(socket, "겐지").start(); new ClientReceiver(socket).start(); } catch (IOException e) { e.printStackTrace(); } } } | cs |