參考網上例子,寫了個socket通訊例子,運行能夠成功java
1.建立兩個普通的java project,直接貼圖以下服務器
2.客戶端代碼以下app
package client; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.Socket; public class Client { public static void main(String args[]) { try{ //建立客戶端套接字 Socket socket = new Socket("127.0.0.1", 9999); //寫入來自socket的輸出流 Writer writer = new OutputStreamWriter(socket.getOutputStream()); writer.write("Hello world"); //刷新輸出流 writer.flush(); writer.close(); socket.close(); }catch(Exception e) { e.printStackTrace(); } } }
3.服務器端代碼以下socket
package server; import java.io.InputStreamReader; import java.io.Reader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String args[]) { try { //建立一個ServerSocket,在端口號9999上監聽客戶端請求 ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); //獲取來自socket的輸入流 Reader reader = new InputStreamReader(socket.getInputStream()); char chars[] = new char[1024]; int len; StringBuilder builder = new StringBuilder(); while ((len = reader.read(chars)) != -1) { builder.append(new String(chars, 0, len)); } System.out.println("Receive from client message=: " + builder); reader.close(); socket.close(); serverSocket.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
4.先run as 服務器端代碼,使服務器運行起來,再運行客戶端代碼,運行結果以下ui
Receive from client message=: Hello world。.net