【发布时间】:2017-03-26 13:37:31
【问题描述】:
我是 java 网络编程的新手,请记住这一点。
我正在尝试开发一个多线程 Java 服务器客户端应用程序。对于初学者,我的目标是仅在单个客户端和服务器之间开发通信通道。在没有线程的情况下,单个客户端-服务器之间的通信可以正常工作。但是当我应用线程时,程序失败了。消息未发送。
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");
}
}
}
我的客户
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");
}
}
}
【问题讨论】:
-
当你写一个多线程的客户端服务器程序时,这段代码是不正确的。当多个客户端连接到一个服务器时,你必须分配一个id,例如。 1,2,3,4 等到每个客户端。更多详细信息请参见此处 [链接] (mrbool.com/creating-a-multithreaded-chat-with-socket-in-java/…)
标签: java multithreading sockets client-server serversocket