十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
用ServerSocket和Socket做了個Server、Client通信的demo,以及學習下在這個demo過程中用到java.net、java.io包下幾個常用的類。

import java.net.*;import java.io.*;public class HttpServer{
public static void main(String[] args){ new HttpServer().start();
}
private ServerSocket serversocket=null;
public HttpServer(){ try{
serversocket=new ServerSocket(5000);//監(jiān)聽客戶端端口5000的socket請求
System.out.println("服務器啟動");
}catch(IOException e){
e.printStackTrace();
}
} public void start(){
Socket socket=null; while(true){ try{
socket=serversocket.accept(); //接受客戶端請求socket
System.out.println("address:"+socket.getInetAddress()+":"+socket.getLocalPort());
OutputStream os =socket.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); //向客戶端發(fā)送一條消息
bw.write("測試服務器通信\n");
bw.flush();
}catch(IOException e){
e.printStackTrace();
System.out.println("連接斷開");
}finally{ try{ if(socket !=null){
socket.close();
}
}catch(IOException e){
}
}
}
}
}import java.net.*;import java.io.*;public class Client{
public static void main(String[] args){
Socket socket=null; try{
socket =new Socket("127.0.0.1",5000);
InputStream is =socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br =new BufferedReader (isr);
String mess=br.readLine();
System.out.println("mess:"+mess);
}catch(IOException e){
e.printStackTrace();
}finally{ try{ if(socket !=null){
socket.close();
}
}catch(IOException e){
}
}
}
}java.net包內幾個常用的類:
ServerSocket、
Socket、
OutputStream、InputStream、
InputStreamReader、OutputStreamWriter、
BufferedReader、BufferedWriter、
InetAddress、
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。