服务端
import java.io.*;
import java.net.*;public class ChatServer {
ServerSocket ss = null;
boolean start = false; public static void main(String[] args) {
ChatServer server = new ChatServer();
server.start();
} public void start() {
try {
ss = new ServerSocket(6666);
start = true;
while (start) { Socket s = null;
s = ss.accept();
System.out.println("一个客户端链接成功");
ClientThread client = new ClientThread(s);
Thread tt = new Thread(client);
tt.start(); }
} catch (IOException e) {
System.out.println("申请绑定端口失败");
}
} class ClientThread implements Runnable {
private Socket s = null;
private DataInputStream dis = null;
private boolean sts = false; public ClientThread(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
sts = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} @Override
public void run() {

while (sts) {
try {
System.out.println("zhi xing dao sssssssssle ma ");
System.out.println(dis.readUTF());
System.out.println("zhi xing dao le ma ");
} catch (EOFException w) {
System.out.println("client close");

} catch (IOException e) {
System.out.println("a client slose");
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(s != null) s.close();
} catch (IOException e1) {
e1.printStackTrace();
} } }

}
}
}
客户端
import java.io.*;
import java.net.*;public class ChatServer {
ServerSocket ss = null;
boolean start = false; public static void main(String[] args) {
ChatServer server = new ChatServer();
server.start();
} public void start() {
try {
ss = new ServerSocket(6666);
start = true;
while (start) { Socket s = null;
s = ss.accept();
System.out.println("一个客户端链接成功");
ClientThread client = new ClientThread(s);
Thread tt = new Thread(client);
tt.start(); }
} catch (IOException e) {
System.out.println("申请绑定端口失败");
}
} class ClientThread implements Runnable {
private Socket s = null;
private DataInputStream dis = null;
private boolean sts = false; public ClientThread(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
sts = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} @Override
public void run() {

while (sts) {
try {
System.out.println("zhi xing dao sssssssssle ma ");
System.out.println(dis.readUTF());
System.out.println("zhi xing dao le ma ");
} catch (EOFException w) {
System.out.println("client close");

} catch (IOException e) {
System.out.println("a client slose");
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(s != null) s.close();
} catch (IOException e1) {
e1.printStackTrace();
} } }

}
}
}

解决方案 »

  1.   

    你的服务器问题不大,主要是你客户端有问题,很明显你的客户端是服务器的翻版,指明几点:1.客户端是不需要ServerSocket的,并且Socket的构造方法需要指明ip和端口号如Socket mysocket=new Socket("127.0.0.1",4331);2.客户端是不需要监听的……
    你主要是没有搞明白客户端和服务器的机制,希望我说的对你有启示!