當前位置:編程學習大全網 - 編程語言 - socket服務端如何使用多線程

socket服務端如何使用多線程

import java.io.*;

import java.net.*;

public class ChatServer {

boolean started = false;

ServerSocket ss = null;

public static void main(String[] args) {

new ChatServer().start();

}

public void start() {

try {

ss = new ServerSocket(8888);

started = true;

} catch (BindException e) {

System.exit(0);

} catch (IOException e) {

e.printStackTrace();

}

try {

while(started) {

Socket s = ss.accept();

Client c = new Client(s);

System.out.println("a client connected!");

new Thread(c).start();

//dis.close();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

ss.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

class Client implements Runnable {

private Socket s;

private DataInputStream dis = null;

private boolean bConnected = false;

public Client(Socket s) {

this.s = s;

try {

dis = new DataInputStream(s.getInputStream());

bConnected = true;

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void run() {

try {

while(bConnected) {

String str = dis.readUTF();

System.out.println(str);

}

} catch (EOFException e) {

System.out.println("Client closed!");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(dis != null) dis.close();

if(s != null) s.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

}

}

  • 上一篇:山東省普通中小學規範辦學十五條規定(征求意見稿)
  • 下一篇:南京java培訓哪家好?
  • copyright 2024編程學習大全網