-
Java - Network - ChatJava 2018. 2. 6. 08:44반응형< Chat >import java.io.IOException;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;public class ChatServer {public static void main(String[] args) {try {//1. 서버소켓 생성+특정 IP 개방ServerSocket server = new ServerSocket(5001);System.out.println("연결 요청 대기");//2. 연결 수락Socket socket = server.accept();System.out.println("연결 수락");//3. 메시지가 오면 받아서 읽고Receiver recv = new Receiver(socket);recv.start();//4. 보낼 메시지가 있으면 보낸다.Sender sender = new Sender(socket);sender.start();} catch (IOException e) {e.printStackTrace();}}}import java.net.Socket;public class ChatClient {public static void main(String[] args) {try {//1. 소켓생성+접속 요청Socket socket = new Socket("localhost",5001);//2. 보낼 메시지 보내고Sender sender = new Sender(socket);sender.start();//3. 받을 메시지 받고Receiver recv = new Receiver(socket);recv.start();} catch (Exception e) {e.printStackTrace();}}}< Send, Receive MSG >import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.Socket;import java.util.Scanner;public class Sender extends Thread {private Socket socket;OutputStream os = null;OutputStreamWriter writer = null;Scanner scan = null;public Sender(Socket socket) {this.socket = socket;}@Overridepublic void run() {String msg;try {//1. 스트림 준비os = socket.getOutputStream();writer = new OutputStreamWriter(os, "UTF-8");while(os != null) {scan = new Scanner(System.in);//스캐너 준비msg = scan.nextLine();//입력값 읽어오기writer.write(msg);//내보내기writer.flush();}}catch(Exception e) {try {writer.close();os.close();} catch (IOException e1) {}}}}import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.Socket;public class Receiver extends Thread {private Socket socket;InputStream is = null;InputStreamReader reader = null;public Receiver(Socket socket) {this.socket = socket;}@Overridepublic void run() {//1. 스트림 준비try {is = socket.getInputStream();reader = new InputStreamReader(is,"UTF-8");char[] arr = new char[100];while(is != null) {int len = reader.read(arr);String msg = new String(arr);String result = msg.substring(0,len);System.out.println("상대> "+result);//3. 읽은 내용 출력arr = new char[100];// 긴문 장 후 짧은 문장이 올 경우 배열에 남은 값과 섞이는 것을 방지}} catch (IOException e) {try {is.close();reader.close();} catch (IOException e1) {}e.printStackTrace();}}}반응형
'Java' 카테고리의 다른 글
Java - UDP (0) 2018.02.06 Java - Network, MultiChat (0) 2018.02.06 Java - Network (0) 2018.02.05 Java - Stream IO (0) 2018.02.02 Java - File I/O (0) 2018.02.01 댓글