1. 程式人生 > >Socket程式設計java[簡單易懂],附帶Android Studio 專案聊天例項

Socket程式設計java[簡單易懂],附帶Android Studio 專案聊天例項

伺服器端

package socket_util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public void run() throws IOException{
        //服務端socket物件
ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress("127.0.0.1",1234)); while(true) { Socket socket = serverSocket.accept(); //接收客戶端發來的資料 InputStream is = socket.getInputStream(); InputStreamReader isr = new
InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String str = null; if( (str = br.readLine()) != null) { System.out.println(str); } socket.close(); } } public static void main(String[] args) { Server s = new
Server(); System.out.println("伺服器端開啟"); try { s.run(); } catch (IOException e) { System.out.println("IO異常"); e.printStackTrace(); } } }

客戶端

package socket_util;

import java.io.IOException;
import java.net.Socket;

public class Client {
    public void send(String data) throws IOException {
        //建立socket物件,指定ip、port
        Socket socket = new Socket("127.0.0.1", 1234);
        //將資料傳到輸出管道位元組流傳送到伺服器端
        socket.getOutputStream().write(data.getBytes());
        //清空IO管道重的快取資料
        socket.getOutputStream().flush();
        socket.close();
    }

    public static void main(String[] args) {
        Client c = new Client();
        try {
            c.send("123456789,nimabinijiehunlema");
            System.out.println("傳送成功");
        } catch (IOException e) {
            System.out.println("IO異常");
            e.printStackTrace();
        }
    }
}

掃描伺服器端是否開啟

package socket_util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/*
 * 必須在伺服器端開啟的時候才能掃描成功
 */
public class ScanPorts {
    private int minPort, maxPort;

    public ScanPorts(int minPort, int maxPort) {
        this.minPort = minPort;
        this.maxPort = maxPort;
    }
    public void run() throws IOException {
        for(int i = minPort; i <= maxPort; i++) {
            Socket socket = new Socket();
            SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", i);
            socket.connect(socketAddress, 50);
            System.out.println(i + ":ok");
            socket.close();
        }
    }

    public static void main(String[] args) {
        ScanPorts sc = new ScanPorts(1234, 1234);
        try {
            sc.run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

執行結果截圖

  • 執行伺服器端Server.java
    這裡寫圖片描述

  • 執行掃描端ScanPorts.java
    這裡寫圖片描述

  • 執行伺服器端Client.java
    這裡寫圖片描述

  • 這是開啟之前伺服器端的控制檯輸出,會顯示傳送來的資料
    這裡寫圖片描述

專案聊天APP例項