Skip to content

Instantly share code, notes, and snippets.

@junsuk5
Created February 27, 2017 04:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save junsuk5/f0ff2298e17853dc48e89f2dfc7bd985 to your computer and use it in GitHub Desktop.
Save junsuk5/f0ff2298e17853dc48e89f2dfc7bd985 to your computer and use it in GitHub Desktop.
Java 소켓 통신 예제
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* 1 대 1 소켓 통신 클라이언트 예제
*/
public class Client {
private Socket mSocket;
private BufferedReader mIn;
private PrintWriter mOut;
public Client(String ip, int port) {
try {
// 서버에 요청 보내기
mSocket = new Socket(ip, port);
System.out.println(ip + " 연결됨");
// 통로 뚫기
mIn = new BufferedReader(
new InputStreamReader(mSocket.getInputStream()));
mOut = new PrintWriter(mSocket.getOutputStream());
// 메세지 전달
mOut.println("응답하라!!");
mOut.flush();
// 응답 출력
System.out.println(mIn.readLine());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
// 소켓 닫기 (연결 끊기)
try {
mSocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
String ip = "192.168.0.10";
int port = 5555;
new Client(ip, port);
}
}
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 1 대 1 소켓 통신 서버 예제
*/
public class Server {
private ServerSocket mServerSocket;
private Socket mSocket;
private BufferedReader mIn; // 들어오는 통로
private PrintWriter mOut; // 나가는 통로
public Server() {
try {
mServerSocket = new ServerSocket(5555);
System.out.println("서버 시작!!!");
// 스레드가 멈춰 있고
// 연결 요청이 들어오면 연결
mSocket = mServerSocket.accept();
System.out.println("클라이언트와 연결 됨");
mIn = new BufferedReader(
new InputStreamReader(mSocket.getInputStream()));
mOut = new PrintWriter(mSocket.getOutputStream());
// 클라이언트에서 보낸 문자열 출력
System.out.println(mIn.readLine());
// 클라이언트에 문자열 전송
mOut.println("전송 잘 되었음");
mOut.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 소켓 닫기 (연결 끊기)
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
mServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Server server = new Server();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment