서버측 코드:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { ServerSocket server; try{ server = new ServerSocket(1111); Socket socket = server.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); System.out.println(br.readLine()); br.close(); socket.close(); server.close(); }catch (Exception e) { System.out.println(e); } } }
클라이언트측 코드:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; public class Client { public static void main(String[] args) { Socket socket; PrintStream ps; try { socket = new Socket("127.0.0.1",1111); System.out.println("connect successfully..."); System.out.println("Please input some WORDS to server:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String content = null; try { content = br.readLine(); } catch (Exception e) { } ps = new PrintStream(socket.getOutputStream(),true,"UTF-8"); ps.print(content); socket.close(); } catch (Exception e) { System.out.println(e); } } }
Java 기반 소켓 통신 예제 코드 관련 기사를 더 보려면 PHP 중국어를 참고하세요. 웹사이트!