首页 > 代码库 > 实现多线程sokect
实现多线程sokect
上一篇文章说到怎样写一个最简单的Java Socket通信,但是在上一篇文章中的例子有一个问题就是Server只能接受一个Client请求,当第一个Client连接后就占据了这个位置,后 续Client不能再继续连接,所以需要做些改动,当Server没接受到一个Client连接请求之后,都把处理流程放到一个独立的线程里去运行,然后 等待下一个Client连接请求,这样就不会阻塞Server端接收请求了。每个独立运行的程序在使用完Socket对象之后要将其关闭。具体代码如下:
[java] view plaincopyprint?
- package com.googlecode.garbagecan.test.socket.sample2;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class MyServer {
- public static void main(String[] args) throws IOException {
- ServerSocket server = new ServerSocket(10000);
- while (true) {
- Socket socket = server.accept();
- invoke(socket);
- }
- }
- private static void invoke(final Socket client) throws IOException {
- new Thread(new Runnable() {
- public void run() {
- BufferedReader in = null;
- PrintWriter out = null;
- try {
- in = new BufferedReader(new InputStreamReader(client.getInputStream()));
- out = new PrintWriter(client.getOutputStream());
- while (true) {
- String msg = in.readLine();
- System.out.println(msg);
- out.println("Server received " + msg);
- out.flush();
- if (msg.equals("bye")) {
- break;
- }
- }
- } catch(IOException ex) {
- ex.printStackTrace();
- } finally {
- try {
- in.close();
- } catch (Exception e) {}
- try {
- out.close();
- } catch (Exception e) {}
- try {
- client.close();
- } catch (Exception e) {}
- }
- }
- }).start();
- }
- }
下面是Client程序代码:
[java] view plaincopyprint?
- package com.googlecode.garbagecan.test.socket.sample2;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class MyClient {
- public static void main(String[] args) throws Exception {
- Socket socket = new Socket("localhost", 10000);
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter out = new PrintWriter(socket.getOutputStream());
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- while (true) {
- String msg = reader.readLine();
- out.println(msg);
- out.flush();
- if (msg.equals("bye")) {
- break;
- }
- System.out.println(in.readLine());
- }
- socket.close();
- }
- }
测试,首先运行MyServer类,然后运行两个MyClient类,然后分别在每个MyClient的提示符下输入字符串,就可以看到Server可以分别接收处理每个Client的请求了。
实现多线程sokect
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。