程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> Java實現的基於socket通信的實例代碼

Java實現的基於socket通信的實例代碼

編輯:JAVA編程入門知識

服務器端代碼:

代碼如下:

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

 public class Server {
     public static void main(String[] args) {
         ServerSocket server;
         try{
             server = new ServerSocket(1111);
             Socket socket = server.accept();

             BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
             System.out.println(br.readLine());
             br.close();
             socket.close();
             server.close();
         }catch (Exception e) {
             System.out.println(e);
         }
     }
 }

客戶端代碼:

代碼如下:

import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.io.PrintStream;
 import java.net.Socket;

 public class Client {
     public static void main(String[] args) {
         Socket socket;
         PrintStream ps;
         try {
             socket = new Socket("127.0.0.1",1111);
             System.out.println("connect successfully...");
             System.out.println("Please input some WORDS to server:");
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             String content = null;
             try {
                 content = br.readLine();
             } catch (Exception e) {

             }
             ps = new PrintStream(socket.getOutputStream(),true,"UTF-8");
             ps.print(content);

             socket.close();
         } catch (Exception e) {
             System.out.println(e);
         }
     }
 }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved