1. 程式人生 > >(TCP)控制檯迴圈輸入資料 傳送給 服務端

(TCP)控制檯迴圈輸入資料 傳送給 服務端

1 . 客戶端

package com.qf.demo4;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.qf.demo3.Util;

/**
 * 控制檯迴圈輸入資料 傳送給 服務端
 * 
 * @author Administrator
 *
 */
public
class Client { public static void main(String[] args) { // 1 建立快遞點 Socket socket = null; OutputStream os = null; InputStream is = null; try { socket = new Socket("10.0.143.51", 8888); // 2 準備要傳送的資料 Scanner scanner = new Scanner(System.in); // 3 獲得快遞員
os = socket.getOutputStream(); is = socket.getInputStream(); while (true) { String data = scanner.next(); os.write(data.getBytes()); os.flush(); if ("over".equals(data)) { break; } // 收到回信
byte[] bs = new byte[1024]; int num = is.read(bs); String reault = new String(bs, 0, num); System.out.println("伺服器回覆的資料是 : " + reault); if ("over".equals(reault)) { break; } } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { Util.closed(null, socket, is, os); } } }

2 .伺服器端,注意while中的程式碼,在while中回覆資訊

package com.qf.demo4;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import com.qf.demo3.Util;

public class Server {

    public static void main(String[] args) {
        // 1 建立 服務端的socket
        ServerSocket serverSocket = null;
        Socket socket =null;
        InputStream is =null;
        OutputStream os  = null;
        try {
             serverSocket = new ServerSocket(8888);
            // 2 等待接收客戶端的資料
             socket = serverSocket.accept();
             is = socket.getInputStream();
             os  =  socket.getOutputStream();
            Scanner scanner = new Scanner(System.in);
            // 3  讀取資訊
            while(true){
                byte[] bs = new byte[1024];
                //會接著上次讀取的結束位置往後讀取
                int num = is.read(bs);
                String string = new String(bs, 0, num);
                System.out.println("客戶端傳送了: "+string);
                if("over".equals(string)){
                    break;
                }

                // 以下是回覆資料
                String result = scanner.next();
                os.write(result.getBytes());
                os.flush();
                if("over".equals(result)){
                    break;
                }

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            Util.closed(serverSocket, socket, is, os);
        }

    }
}