본문 바로가기

Java

소켓 프로그래밍 실습

갑자기 채팅 프로그램을 짜보고 싶어서, 유투브 보면서 소스 따라하기가 의외로 재미 있어서 놀람.



Server

package chat1;


import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;


public class ServerTest {

private ServerSocket serverSocket;

private Socket clientSocket;

private DataInputStream dataInputStream;

private DataOutputStream dataOutputStream;

public void serverSetting(){

try {

System.out.println("서버 start...");

// localhost 10002 포트

serverSocket = new ServerSocket(10002);

clientSocket = serverSocket.accept();

// 소켓의 접속완료

System.out.println("클라이언트 소켓 연결");

} catch (Exception e) {

e.printStackTrace();

}

}

public void closeAll(){

try {

serverSocket.close();

clientSocket.close();

dataInputStream.close();

dataOutputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public void streamSetting(){

try {

dataInputStream = new DataInputStream(clientSocket.getInputStream());

dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());

} catch (Exception e) {

e.printStackTrace();

}

}

public String dataRecv(){

try {

return dataInputStream.readUTF();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

public void dataSend(String sendData){

try {

dataOutputStream.writeUTF(sendData);

} catch (IOException e) {

e.printStackTrace();

}

}

public ServerTest(){

serverSetting();

streamSetting();

System.out.println(dataRecv());

dataSend("굿 잡 맨");

closeAll();

}

public static void main(String[] args){

new ServerTest();

}


}



Client

package chat1;


import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.Socket;


public class ClientTest {

private Socket clientSocket;

private DataInputStream dataInputStream;

private DataOutputStream dataOutputStream;

public void connect(){

try {

clientSocket = new Socket("192.168.0.1", 10002);

System.out.println("접속 완료!");

} catch (Exception e) {

e.printStackTrace();

}

}

public void streamSetting(){

try {

dataInputStream = new DataInputStream(clientSocket.getInputStream());

dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());

} catch (Exception e) {

e.printStackTrace();

}

}

public String dataRecv(){

try {

return dataInputStream.readUTF();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

public void dataSend(String sendData){

try {

dataOutputStream.writeUTF(sendData);

} catch (IOException e) {

e.printStackTrace();

}

}


public ClientTest() {

connect();

streamSetting();

dataSend("안녕 난 클라이언트야");

System.out.println(dataRecv());

}

public static void main(String[] args){

new ClientTest();

}

}



아래 유투브 강의를 참고했다.

https://www.youtube.com/watch?v=LEngL3wg-8k


이어서 채팅 프로그램을 구현한다.