//先寫個客戶端的應(yīng)用
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) {
try {
// 在5432端口打開服務(wù)器連接
// 在這里用localhost與127.0.0.1是一個意思
Socket s1 = new Socket("127.0.0.1", 5432);
// 對這個端口連接一個reader,注意端口不能夠占用別的
BufferedReader br = new BufferedReader(
new InputStreamReader(s1.getInputStream()));
// 讀取輸入的數(shù)據(jù)并且打印在屏幕上
System.out.println(br.readLine());
//當(dāng)完成時關(guān)閉流和連接
br.close();
s1.close();
} catch (ConnectException connExc) {
System.err.println("Could not connect to the server.");
} catch (IOException e) {
// ignore
}}}
//這是服務(wù)端的應(yīng)用
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) {
ServerSocket s = null;
// 注冊服務(wù)端口為5432
try {
s = new ServerSocket(5432);
} catch (IOException e) {
e.printStackTrace();
}
// 運(yùn)行監(jiān)聽器并接收,永遠(yuǎn)循環(huán)下去。因?yàn)榉?wù)器總要開啟的
while (true) {
try {
// 等待一個連接的請求
Socket s1 = s.accept();
// 得到端口的輸出流
OutputStream s1out = s1.getOutputStream();
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(s1out));
// 發(fā)送一個字符串
bw.write("百家拳軟件項(xiàng)目研究室歡迎您!\n");
// 關(guān)閉這個連接, 但不是服務(wù)端的socket
bw.close();
s1.close();
} catch (IOException e) {
e.printStackTrace();
}}}} |