我是java网络编程的新手,请记住这一点。
我正在尝试开发一个多线程的Java服务器客户端应用程序。对于Starters,我的目标是仅在单个客户端和服务器之间开发通信通道。没有线程,单个客户端 - 服务器之间的通信工作正常。当我应用线程时程序失败。邮件未发送。
MyServer.java
class MyServer {
public static void main(String[] args) {
try {
ServerSocket svc = new ServerSocket(4567);
System.out.println("Server Waiting at Port 4567");
do {
Socket sock = svc.accept();
MyServerThread thread = new MyServerThread(sock);
}while(true);
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
MyServerThread.java
class MyServerThread extends Thread{
Socket sock;
public MyServerThread(Socket sock) {
this.sock = sock;
}
public void run() {
try {
PrintWriter pw = new PrintWriter(sock.getOutputStream());
Scanner cd = new Scanner(sock.getInputStream());
Scanner kb = new Scanner(System.in);
do {
String clientstr = cd.nextLine();
System.out.println("Client: "+clientstr);
if(clientstr.equalsIgnoreCase("quit")) {
break;
}
String str = kb.nextLine();
pw.println(str);
pw.flush();
}while(true);
sock.close();
pw.close();
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
MyClient
class MyClient3 {
public static void main(String[] args) {
try {
InetAddress object = InetAddress.getByName("192.168.18.125");
Socket sock = new Socket(object, 4567);
PrintWriter pw = new PrintWriter(sock.getOutputStream());
Scanner cd = new Scanner(sock.getInputStream());
Scanner kb = new Scanner(System.in);
do {
String str = kb.nextLine();
pw.println(str);
pw.flush();
String strserver = cd.nextLine();
System.out.println("Server: "+strserver);
if(strserver.equalsIgnoreCase("quit")) {
break;
}
}while(true);
sock.close();
pw.close();
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
答案 0 :(得分:1)
您最直接的问题是,在创建MyServerThread后,您不会在线程上调用Thread#start()。但是,通常您不应该创建扩展线程的类。您应该创建一个Runnable,并将其传递给Thread#new(Runnable)。