1. 程式人生 > >Java Socket簡單例項

Java Socket簡單例項

一 伺服器端Server.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket=new ServerSocket(6789);
		while(true){
			Socket socket=serverSocket.accept();
			InputStream inputStream=socket.getInputStream();
			BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
			String string=br.readLine();
			System.out.println("客戶端說:"+string);
			br.close();
			inputStream.close();
			socket.close();
		}
	}
}


二 客戶端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;

public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket socket=new Socket("127.0.0.1", 6789);
		OutputStream outputStream=socket.getOutputStream();
		BufferedWriter bWriter=new BufferedWriter(new OutputStreamWriter(outputStream));
		bWriter.write("伺服器你好啊!");
		bWriter.close();
		outputStream.close();
		socket.close();
	}
}


三 結果

執行客戶端程式三次,結果如下:

客戶端說:伺服器你好啊!
客戶端說:伺服器你好啊!
客戶端說:伺服器你好啊!