cs 모드에서 socket 간단한 설명

2374 단어
cs 모드에서 socket 간단한 설명
Socket 프로그래밍은 cs 모드에서 매우 중요한 tcp/ip 통신 기술이다.모바일 클라이언트로서 개발하는 것이 특히 중요하다.Socket 커뮤니케이션의 메커니즘에 대해 간략하게 설명합니다.
cs모드에서 socket의 원리는 먼저 서버에서 ServerSocket 대상을 끊고 ServerSocket 대상은 제정된 포트를 감청하기 시작한다. 클라이언트 소켓이 이 포트에 연결을 요청하고 클라이언트 대상을 얻은 다음에 처리를 하는 것을 알 수 있다.
클라이언트는 서버 측의 ServerSocket을 연결하고 특정한 처리를 하는 것이다.
먼저 다음과 같은 ServerSocket 프로젝트를 만듭니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;




public class ServerSocketDemo {
	
	public static void main(String[] args){
		try {
			//instantiate a ServerSocket objects and listen to the port 8088 
			ServerSocket serverSocket=new ServerSocket(8088);
			//GEt the client object when a client requests
			Socket clientSocket=serverSocket.accept();
			//get the inputStream from ClientSocket
			InputStream inputStream=clientSocket.getInputStream();
			//use Decoration pattern to get a better format object
			Reader inputStreamReader=new InputStreamReader(inputStream);
			BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
			
			System.out.println(bufferedReader.readLine());
			bufferedReader.close();
			serverSocket.close();
		} catch (IOException e) {
			System.out.println("IOException occurs");
			e.printStackTrace();
		}
	}
}

그리고 클라이언트 소켓의 프로젝트로 다른 프로젝트를 새로 만듭니다.
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;




public class ClientSocketDemo {
	
	public static void main(String[] args){
		Socket clientSocket;
		try {
			clientSocket=new Socket("127.0.0.1",8088);
			//when connected to the server socket show the tips
			System.out.println("successfully connected");
			//input the words into io stream and send them to servers
			PrintStream printStream=new PrintStream(clientSocket.getOutputStream());
			printStream.println("hello world");
			clientSocket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

시작할 때 Eclipse를 모두 사용하지 마십시오. 명령줄로 실행 서버의 자바 프로그램을 컴파일하고, Eclipse로 실행 클라이언트의 프로그램을 컴파일하는 것을 권장합니다.먼저 서버를 시작한 다음 클라이언트 프로그램을 시작하는 순서입니다.
Last Modified:2011-12-23

좋은 웹페이지 즐겨찾기