자바 socket 연결 및 데이터 전송 및 수신

5414 단어
/**
 * 
 */
package socketTest2;


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static final int PORT = 12345;//         
    
    public static void main(String[] args) {  
        System.out.println("     ...
"); Server server = new Server(); server.init(); } public void init() { try { ServerSocket serverSocket = new ServerSocket(PORT); while (true) { // , Socket client = serverSocket.accept(); // new HandlerThread(client); } } catch (Exception e) { System.out.println(" : " + e.getMessage()); } } private class HandlerThread implements Runnable { private Socket socket; public HandlerThread(Socket client) { socket = client; new Thread(this).start(); } public void run() { try { // DataInputStream input = new DataInputStream(socket.getInputStream()); String clientInputStr = input.readUTF();// , EOFException // System.out.println(" :" + clientInputStr); // DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print(" :\t"); // String s = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(s); out.close(); input.close(); } catch (Exception e) { System.out.println(" run : " + e.getMessage()); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { socket = null; System.out.println(" finally :" + e.getMessage()); } } } } } }

 
 
/**
 * 
 */
package socketTest2;


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {
    public static final String IP_ADDR = "localhost";//      
    public static final int PORT = 12345;//        
    
    public static void main(String[] args) {  
        System.out.println("     ...");  
        System.out.println("            \"OK\"    ,       
"); while (true) { Socket socket = null; try { // socket = new Socket(IP_ADDR, PORT); // DataInputStream input = new DataInputStream(socket.getInputStream()); // DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print(" : \t"); String str = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(str); String ret = input.readUTF(); System.out.println(" : " + ret); // "OK" if ("OK".equals(ret)) { System.out.println(" "); Thread.sleep(500); break; } out.close(); input.close(); } catch (Exception e) { System.out.println(" :" + e.getMessage()); } finally { if (socket != null) { try { socket.close(); System.out.println("socket is closed"); } catch (IOException e) { socket = null; System.out.println(" finally :" + e.getMessage()); } } } } } }

좋은 웹페이지 즐겨찾기