티스토리 뷰

졸업작품

소켓 통신 예제 - 자바 서버

doublemetal 2013. 5. 14. 01:26

S: Connecting... 이라는 메시지가 출력되고

클라이언트가 붙으면 S: Receiving... 시작으로 여러 문자열들이 출력되는 소스 

출처는 너무 많고 기억도 안남. 웹 검색으로 나오는 소스가 대략 2~3가지인데 그 중에 하나임



package TCPtest;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.InetAddress;

import java.net.ServerSocket;

import java.net.Socket;


public class TCPserver implements Runnable {

public static final int ServerPort = 5555; // ex: 5555


@Override

public void run() {

// TODO Auto-generated method stub

try {

ServerSocket serverSocket = new ServerSocket(ServerPort);

System.out.println("S: Connecting...");

System.out.println(InetAddress.getLocalHost().getHostAddress());

while (true) {

Socket socket = serverSocket.accept();

System.out.println("S: Receiving...");


try {

BufferedReader in = new BufferedReader(

new InputStreamReader(socket.getInputStream()));

String str = in.readLine();

System.out.println("S: Received: '" + str + "'");

PrintWriter out = new PrintWriter(new BufferedWriter(

new OutputStreamWriter(socket.getOutputStream())),

true);

out.println("Server Received " + str);


} catch (Exception e) {

System.out.println("S: Error");

e.printStackTrace();

} finally {

socket.close();

System.out.println("S: Done.");


}

}

} catch (Exception e) {

System.out.println("S: Error");

e.printStackTrace();

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Thread desktopServerThread = new Thread(new TCPserver());

desktopServerThread.start();

}

}


댓글
최근에 올라온 글
최근에 달린 댓글
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
글 보관함