---
# System prepended metadata

title: Client
tags: [JDBC]

---

# Client
###### tags: `JDBC`
package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) {


	Scanner scanner = new Scanner(System.in);
	System.out.println("請輸入主機的IP");
	String host = scanner.nextLine();
	System.out.println("請輸入主機的Port");
	int port = Integer.parseInt(scanner.nextLine());
	
	try ( Socket socket = new Socket(host,port); 
			InputStream is = socket.getInputStream();//取得InputStream
			InputStreamReader isr = new InputStreamReader(is,"UTF8");//編碼InputStreamReader
			BufferedReader br = new BufferedReader(isr);
			OutputStream os = socket.getOutputStream();//送資料getOutputStream
			OutputStreamWriter osw = new OutputStreamWriter(os,"UTF8");//編碼
			BufferedWriter bw = new BufferedWriter(osw);
			
			){
		System.out.println("請輸入傳送的文字,輸入b中斷");
		String message = scanner.nextLine();
		while (message != null) {
			//send message to Server
			message = message + System.lineSeparator();//串換行符號,因為Server也是readLine,需要換行
			bw.write(message);
			bw.flush();
			
			//read message to Server
			String line = br.readLine();
			if(line==null) {
				//表示斷線
				break;
			}
			System.out.println("接收到:"+line);
			System.out.println("請輸入回應的訊息,輸入b中斷");
			message = scanner.nextLine();
			if (message.equalsIgnoreCase("b")) {
				break;
			}
		}
		
	} catch (UnknownHostException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	}

}
