Java 네트워크 프로그래밍 - 서버 측과 클라이언트의 연결 및 정보 전달 실현

7013 단어
1. Client(클라이언트 코드)
package cn.qi.Client;

import java.io.*;
import java.net.Socket;

public class Client {
    Socket clientSocket;
    Client() {}

    public void write() throws IOException {
        //  socket
        clientSocket = new Socket("127.0.0.1",5000);

        //  , socket 
        OutputStream os = clientSocket.getOutputStream();
        //  socket IO , IO 
        PrintWriter pw = new PrintWriter(os);

        pw.write("hello");
        pw.flush();
        //  
        pw.close();

        //  socket 
        clientSocket.close();
    }

    public void read() throws IOException {
        //  socket
        clientSocket = new Socket("127.0.0.1",5000);


        // socket IO
        InputStream is = clientSocket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String st = br.readLine();
        br.close();
        System.out.println(st);

        //  socket 
        clientSocket.close();
    }
}

 
2, Server(서버 측 코드)
package cn.qi.Server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    ServerSocket serverSocket;
    Server() {}

    public void sent() throws IOException {
        //  severSocket, 
        serverSocket = new ServerSocket(5000);


        while(true) {
            // server , , socket
            Socket socket= serverSocket.accept();

            //  , socket 
            OutputStream os = socket.getOutputStream();
            //  socket IO , IO 
            PrintWriter pw = new PrintWriter(os);

            pw.write("hello");
            pw.flush();
            //  
            pw.close();

            //  socket 
            socket.close();
        }

    }

    public void getInfo() throws IOException {
        //  severSocket, 
        serverSocket = new ServerSocket(5000);


        while(true) {
            // server , , socket
            Socket socket= serverSocket.accept();

            // socket IO
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String st = br.readLine();
            br.close();

            System.out.println(st);

            //  socket 
            socket.close();
        }

    }
}

좋은 웹페이지 즐겨찾기