1. 程式人生 > >Java的socket程式設計

Java的socket程式設計

一、原理

伺服器端用serversocket物件監控埠。客戶端用socket物件傳送請求來建立連線,當伺服器端收到請求後,用accecpt()方法生成socket物件來建立連線。

二、客戶端傳送、接受示例

package grammar;
import java.io.*;
import java.net.*;

public class MyServer {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = null;
		PrintWriter pw = null;
		//埠監測物件監測埠;當有請求時生成socket,建立連線
		ServerSocket server = new ServerSocket(8000);
		Socket socket = server.accept();//執行到此方法時,執行緒阻塞。後面的方法先不執行

		//從socket中獲取輸入、輸出物件
		br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		pw = new PrintWriter(socket.getOutputStream(), true);
		//得到輸入
		String str = br.readLine();
		System.out.println("server:" + str);
		pw.println(str);
		//釋放輸入輸出資源
		br.close();
		pw.close();
	}

}
package grammar;
import java.io.*;
import java.net.*;

public class MyClient {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = null;
		PrintWriter pw = null;
		//socket物件表示兩臺電腦之間的網路連線		
		Socket socket = new Socket("localhost",8000);
		//從socket中獲得輸入、輸出物件
		br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		pw = new PrintWriter(socket.getOutputStream(), true);
		//輸出
		pw.println("hell0! I'm zp.");
		pw.flush();
		String str = null;
		while(true){
			//得到輸入
			str = br.readLine();
			if(str != null){
				break;
			}
		}
		System.out.println("client:" + str);
		//釋放輸入輸出資源
		br.close();
		pw.close();
	}

}