package com.lovo.client;java
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;.net
//客戶端---消息的發起方
public class TestClient {對象
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//一、獲得要發送的消息,能夠接收外部輸入
String msg = new Scanner(System.in).next();
//二、獲得Socket對象
Socket sc = null;
try {
sc = new Socket("127.0.0.1",9527);
//三、把消息交給Socket對象---因爲是發送,因此方向是輸出流;發送內容能夠是文本也能夠是二進制數據,因此它
// 提供的是字節流---綜上,必定是OutputStream
// OutputStream out = sc.getOutputStream();
// out.write(msg.getBytes());
// out.flush();//強制輸出
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
bw.write(msg);
bw.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//四、關閉
if(sc != null){
try {
sc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}get
}it