首頁 > 軟體

Java實現簡單的socket通訊教學

2020-12-08 12:09:50

今天學習了一下java如何實現socket通訊,感覺難點反而是在io上,因為java對socket封裝已經很完善了。

今天程式碼花了整個晚上偵錯,主要原因是io的flush問題和命令列下如何執行具有package的類,不過最後問題基本都解決了,把程式碼貼出來供大家參考

server

public class TcpServer {
 public static void main(String[] args) throws Exception {
  ServerSocket server = new ServerSocket(9091);
  try {
   Socket client = server.accept();
   try {
    BufferedReader input =
      new BufferedReader(new InputStreamReader(client.getInputStream()));
    boolean flag = true;
    int count = 1;
 
    while (flag) {
     System.out.println(使用者端要開始發騷了,這是第 + count + 次!);
     count++;
      
     String line = input.readLine();
     System.out.println(使用者端說: + line);
      
     if (line.equals(exit)) {
      flag = false;
      System.out.println(使用者端不想玩了!);
     } else {
      System.out.println(使用者端說: + line);
     }
 
    }
   } finally {
    client.close();
   }
    
  } finally {
   server.close();
  }
 }
}

client

public class TcpClient {
 public static void main(String[] args) throws Exception {
  Socket client = new Socket(127.0.0.1, 9091);
  try {
   PrintWriter output =
     new PrintWriter(client.getOutputStream(), true);
   Scanner cin = new Scanner(System.in);
   String words;
 
   while (cin.hasNext()) {
    words = cin.nextLine();
 
    output.println(words);
 
    System.out.println(寫出了資料: + words);
   }
 
   cin.close();
  } finally {
   client.close();
  }
 }
}

補充知識:Java-Socket通訊 同時JSON傳遞與解析

伺服器端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import net.sf.json.JSONObject;
public class Server_2 {
  public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    InputStreamReader isr;
    BufferedReader br;
    OutputStreamWriter osw;
    BufferedWriter rw;
    try {
      ServerSocket serverSocket=new ServerSocket(4444);
      Socket socket=serverSocket.accept();
      isr=new InputStreamReader(socket.getInputStream());
      br=new BufferedReader(isr);
      String str=br.readLine();
      JSONObject object=JSONObject.fromObject(str);
      System.out.println("ID:"+object.getInt("ID"));
      System.out.println("Name:"+object.getString("name"));
      System.out.println("password:"+object.getString("password"));
      br.close();
      socket.close();
      serverSocket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

客服端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
import net.sf.json.JSONObject;
public class Client_2 {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    InputStreamReader isr;
    BufferedReader br;
    OutputStreamWriter osw;
    BufferedWriter rw;
    try {
      Socket socket = new Socket("localhost", 4444);
      osw = new OutputStreamWriter(socket.getOutputStream());
      rw = new BufferedWriter(osw);
      User user = new User();
      System.out.println("Id:");
      user.setID(in.nextInt());
      in.nextLine();
      System.out.println("Name:");
      user.setName(in.nextLine());
      System.out.println("Password:");
      user.setPassword(in.nextLine());
      JSONObject jsonObject = JSONObject.fromObject(user);
      rw.write(jsonObject.toString()+"n");
      rw.close();
      socket.close();
    } catch (Exception e) {
      // TODO: handle exception
    }
  }
}

User

public class User {
  int ID;
  String name;
  String password;
  public int getID() {
    return ID;
  }
  public void setID(int iD) {
    ID = iD;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
}

以上這篇Java實現簡單的socket通訊教學就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com