socket訪問的小demo
伺服器端
public class ServiceServer {
public static void main(String[] args) throws Exception {
// 建立一個serversocket,繫結到本機的8899埠上
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress("localhost", 8899));
// 接受客戶端的連線請求;accept是一個阻塞方法,會一直等待,到有客戶端請求連線才返回
while (true) {
Socket socket = server.accept();
new Thread(new ServiceServerTask(socket)).start();
}
}
}
public class ServiceServerTask implements Runnable{
Socket socket ;
InputStream in=null;
OutputStream out = null;
public ServiceServerTask(Socket socket) {
this.socket = socket;
}
//業務邏輯:跟客戶端進行資料互動
@Override
public void run() {
try {
//從socket連線中獲取到與client之間的網路通訊輸入輸出流
in = socket.getInputStream();
out = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//從網路通訊輸入流中讀取客戶端傳送過來的資料
//注意:socketinputstream的讀資料的方法都是阻塞的
String param = br.readLine();
GetDataServiceImpl getDataServiceImpl = new GetDataServiceImpl();
String result = getDataServiceImpl.getData(param);
//將呼叫結果寫到sokect的輸出流中,以傳送給客戶端
PrintWriter pw = new PrintWriter(out);
pw.println(result);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class GetDataServiceImpl {
public String getData(String param){
return "ok-"+param;
}
}
客戶端
public class ServiceClient {
public static void main(String[] args) throws Exception {
/*ServiceIterface service = ProxyUtils.getProxy(ServiceIterface.class,"methodA",hostname,port);
Result = service.methodA(parameters);*/
// 向伺服器發出請求建立連線
Socket socket = new Socket("localhost", 8899);
// 從socket中獲取輸入輸出流
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
pw.println("hello");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String result = br.readLine();
System.out.println(result);
inputStream.close();
outputStream.close();
socket.close();
}
}