Java 基於TCP/IP 實現簡單的 socket 通訊
阿新 • • 發佈:2019-01-08
Server.java
package com.learn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 基於TCP協議的Socket通訊,實現使用者登入 服務端
*
*/
public class Server {
public static void main(String[] args) {
try {
// 1.建立一個伺服器端的 Socket,即 ServerSocket,指定繫結的端,並監聽
ServerSocket server = new ServerSocket(8888);
// 2.呼叫 accept 方法開始監聽,等待客戶端連線
System.out.println("****伺服器開始啟動,等待客戶端上線****");
Socket socket = server.accept();
// 3.獲取一個輸入流,用來讀取客戶端所傳送的登入資訊
InputStream is = socket.getInputStream();// 位元組輸入流
InputStreamReader isr = new InputStreamReader(is);// 將位元組流轉為
BufferedReader br = new BufferedReader(isr);// 為輸入流新增緩衝
String info = null;
while ((info = br.readLine()) != null) {
System.out.println("我是伺服器,客戶端說" + info);
}
socket.shutdownInput();// 關閉輸入流
// 4.獲取輸出流
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);// 包裝列印流
pw.write("好的,我收到訊息了,你可以出去玩了");
pw.flush();
socket.shutdownOutput();
// 5.關閉資源
pw.close();
br.close();
isr.close();
is.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client.java
package com.learn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/*
* 客戶端
* */
public class Client {
public static void main(String[] args) {
try {
// 1.建立 socket 指定伺服器地址和端
Socket client = new Socket("192.168.6.184", 8888);
// 2.客戶端向伺服器傳送登入資訊
OutputStream os = client.getOutputStream();// 位元組輸出流
PrintWriter pw = new PrintWriter(os);
pw.write("使用者名稱: admin;密碼:123");
pw.flush();
client.shutdownOutput();// 關閉輸出流
// 3. 獲取輸入流
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String info = null;
while ((info = br.readLine()) != null) {
System.out.println("伺服器發來訊息說:" + info);
}
// 3.關閉其他資源
pw.close();
os.close();
client.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
執行時,仍然需要先來執行服務端,然後再執行客戶端即可