多线程Socket编程

来源:互联网 发布:小说 超级基因优化液 编辑:程序博客网 时间:2024/04/30 20:28

刚刚使用多线程知识和Socket编程知识简单的编了一个程序:echo程序

功能:将客户端ID和提交给服务器的内容返回给客户端

 

//服务器端:

package demo5;

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

 

public class Server {
 ServerSocket ssocket;
 int id = 0;// 标记客户端ID
 
 public Server() throws IOException {
  ssocket = new ServerSocket();
  ssocket.setReuseAddress(true);
  ssocket.bind(new InetSocketAddress(888));
  System.out.println("服务器已经启动");
 }

 public void service() throws IOException {
  Socket socket = null;
  int count = 1;
  while (count <= 3) {
   count++;
   socket = ssocket.accept();
   id++;
   new MyThread(socket, id).start();
  }
 }

 public static void main(String args[]) throws IOException {
  new Server().service();
 }
}

 

class MyThread extends Thread {
 Socket socket;
 int id;

 public MyThread(Socket socket, int id) {
  this.socket = socket;
  this.id = id;
 }

 public void run() {
  BufferedReader br = GetIO.getReader(socket);
  PrintWriter pw = GetIO.getWriter(socket);

  String msg;
  try {
   while ((msg = br.readLine()) != null) {
    pw.println("echo[" + id + "]" + msg);
    pw.flush();
    if (msg.equals("bye"))
     break;
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    br.close();
    pw.close();
    socket.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

//客户端:


package demo5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

 public Client(){
  try{
  Socket socket = new Socket("localhost", 888);
  System.out.println("已连接……");
  BufferedReader br = GetIO.getReader(socket);
  BufferedReader localbr = new BufferedReader(new InputStreamReader(System.in));
  PrintWriter pw = GetIO.getWriter(socket);

  String msg;
  while ((msg = localbr.readLine()) != null) {
   pw.println(msg);
   pw.flush();
   System.out.println(br.readLine());
   if (msg.equals("bye"))
    break;
  }
  br.close();
  localbr.close();
  pw.close();
  socket.close();
  }catch(UnknownHostException ex){}
  catch(IOException ioex){}
 }
 public static void main(String[] args)   {
  new Client();
 }
}

 

运行结果://粗体字为用户输入部分

已连接……
hello world
echo[3]hello world
bye
echo[3]bye

原创粉丝点击