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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.