티스토리 뷰

Java

Java Socket 통신프로그램 소스

일상의 기록을 남긴다 2017. 9. 14. 14:50

# 서버 소스


package org.perte.socket;


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class MakeServerSocket {

ServerSocket serverSocket = null;

Socket socket = null;

PrintWriter writer = null;

BufferedReader reader = null;

String lineStr;

public MakeServerSocket() {

try {

serverSocket = new ServerSocket(8314); // 괄호 안은 사용할 포트번호

while (true) {

socket = serverSocket.accept();

System.out.println("Client 요청");

writer = new PrintWriter(socket.getOutputStream(), true);

reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while ((lineStr = reader.readLine()) != null) {

writer.write(lineStr);

System.out.println("input : " + lineStr);

}

writer.close();

reader.close();

socket.close();

}

} catch (Exception e) {}

}

public static void main(String[] args) {

new MakeServerSocket();

}

}


==============================================================

# 클라이언트 소스


package org.perte.socket;


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;


public class MakeClientSocket {


Socket socket = null;

PrintWriter writer = null;

BufferedReader reader = null;

public MakeClientSocket() {

try {

socket = new Socket("localhost", 8314); // 1번째 파라미터는 접속할 서버의 주소(IP), 2번째 파라미터는 포트번호

writer = new PrintWriter(socket.getOutputStream(), true);

reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String str = null;

BufferedReader sReader = new BufferedReader(new InputStreamReader(System.in));

while ((str = sReader.readLine()) != null) {

writer.println(str);

System.out.println("output : " + str);

}

writer.close();

reader.close();

sReader.close();

socket.close();

} catch (Exception e) {}

}

public static void main(String[] args) {

new MakeClientSocket();

}

}



공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함