Java的Socket通信(多Clients/Server模型)
生活随笔
收集整理的這篇文章主要介紹了
Java的Socket通信(多Clients/Server模型)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
所謂多clients/Server模型,就是說一個server程序可以與多個client連接,對各個client的事務進行處理。其他的不說了,直接上代碼,大家應該可以看懂的。這是我在vijio上“偷”測試數據的程序,把Main程序(也就是client)叫上去,就可以把讀入的測試數據發到我電腦上的Receiver上來
Client端程序
import java.io.*; import java.net.*; import java.util.*;public class Main {public static void main(String[] args) throws Exception{// TODO Auto-generated method stubSocket socket = new Socket("***.***.***.***", 4700);PrintWriter os = new PrintWriter(socket.getOutputStream());Scanner sc = new Scanner(System.in);int n, c;n = sc.nextInt();c = sc.nextInt();int[] fa = new int[n];for (int i = 1; i <= n-1; i++) fa[i] = sc.nextInt();sc.close();os.println(String.valueOf(n));os.println(String.valueOf(c));for (int i = 1; i <= n-1; i++) os.println(String.valueOf(fa[i]));os.flush();os.close();socket.close();}}服務器端
import java.io.*; import java.net.*;public class Receiver {public static void main(String[] args) throws Exception{// TODO Auto-generated method stubServerSocket server = new ServerSocket(4700);for (int i = 0; i < 20; i++){Socket socket = server.accept();Runnable r = new ThreadHandler(socket, i);Thread t = new Thread(r);t.start();}server.close();} }class ThreadHandler implements Runnable {private Socket socket;private int num;public ThreadHandler(Socket i, int index){socket = i;num = index;}@Overridepublic void run(){// TODO Auto-generated method stubtry{BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));FileWriter out = new FileWriter(new File("Input/input" + num + ".txt"));String tmp;int n;tmp = is.readLine();n = Integer.parseInt(tmp);out.write(tmp + "\n");out.write(is.readLine() + "\n");for (int j = 1; j <= n-1; j++){out.write(is.readLine() + "\n");}out.flush();out.close();is.close();socket.close(); } catch (Exception e){e.printStackTrace();}}}總結
以上是生活随笔為你收集整理的Java的Socket通信(多Clients/Server模型)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P1965 夜夜的数据加强 题解
- 下一篇: sublime配置运行python文件的