日期:2014-05-20  浏览次数:20731 次

用socket实现多线程server
用socket实现多线程server,我现在写好了server。如何实现多线程,给个思路。谢谢

------解决方案--------------------
http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html

lz看最下面
KKMultiServer和KKMultiServerThread
前面还有客户端的多线程
------解决方案--------------------
package goin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;

public class GoinServer {
static final int DEFAULT_PORT = 3135;

static ServerSocket serverSocket;

static Vector <Socket> connections;

static Vector <ClientProc> clients;

public static void sendAll(String s) {
if (connections != null) {
for (Enumeration e = connections.elements(); e.hasMoreElements();) {// send
// the
// msg
// to
// every
// client
// sockets
try {
PrintWriter pw = new PrintWriter(((Socket) e.nextElement())
.getOutputStream());
pw.println(s);
pw.flush();
} catch (IOException ex) {
}
}
}
System.out.println( "sendAll: " + s);
}

public static boolean sendOne(String name, String msg) {
if (clients != null) {
for (Enumeration e = clients.elements(); e.hasMoreElements();) {
ClientProc cp = (ClientProc) e.nextElement();
if ((cp.getName()).equals(name)) {// send the msg to a special
// client socket.
try {
PrintWriter pw = new PrintWriter((cp.getSocket())
.getOutputStream());
pw.println(msg);
pw.flush();
return true;
} catch (IOException ioe) {
}
}
}
}
return false;
}

public static void addConnection(Socket s, ClientProc cp) {
if (connections == null) {
connections = new Vector <Socket> ();
}
connections.addElement(s);

if (clients == null) {
clients = new Vector <ClientProc> ();
}
clients.addElement(cp);
}

public static void deleteConnection(Socket s, ClientProc cp)
throws IOException {
if (connections != null) {
connections.removeElement(s);
s.close();
}
if (clients != null) {
clients.removeElement(cp);
}
}

public static Vector getClients() {
return clients;
}

public static void main(String[] arg) {

int port = DEFAULT_PORT;
try {
serverSocket = new ServerSocket(port);
System.out.println( "Goin server has started! ");
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
while (true) {
try {
Socket cs = serverSocket.accept();

ClientProc cp = new ClientProc(cs);// for every user, the
// server start a thread to
// communicate with he/she.

Thread ct = new Thread(cp);
ct.start();// the thread take a socket of one user start here.

addConnection(cs, cp);// make a communicate channel between
// user and server.
} catch (IOException e) {
System.err.println(e);
}
}
}
}

// ClientProc deal the data exchange logic between users and the server.
class ClientProc implements Runnable {