我正尝试在java中编写多线程客户端服务器聊天应用程序。 我只想创建两个线程,从每个线程发送一些号码,并从服务器获取相同的号码。但有些事情出错了。 Client sends numbers just from one thread and Server returns not all numbersjava中的多线程客户端服务器聊天应用程序
下面是客户端代码
import java.io.*;
import java.net.*;
public class Client implements Runnable{
private Socket clientSocket = null;
private DataInputStream input = null;
private PrintStream output = null;
private DataInputStream inputLine = null;
private int id;
public Client(int id){
this.id = id;
}
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("The client started. Type any text. To quit it type 'Ok'.");
Client a = new Client(1);
Thread one = new Thread(a);
Client b = new Client(2);
Thread two = new Thread(b);
one.start();
two.start();
one.join();
two.join();
}
public void run() {
System.out.println("hi from thread" + id);
try {
clientSocket = new Socket("localhost", 4444);
output = new PrintStream(clientSocket.getOutputStream());
input = new DataInputStream(clientSocket.getInputStream());
inputLine = new DataInputStream(new BufferedInputStream(System.in));
}
catch(IOException e){
System.out.println(e);
}
String responseLine;
try{
for(int i = 0; i < 10; i++){
output.println(id + " " + i);
System.out.println("sended:" + id + " " + i);
responseLine = input.readLine();
System.out.println("received: " + responseLine);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
和服务器代码
import java.io.*;
import java.net.*;
public class Server implements Runnable{
private static ServerSocket MyService = null;
private DataInputStream input = null;
private PrintStream output = null;
private String line;
private static Socket serviceSocket = null;
public static void main(String[] args) throws IOException {
try{
MyService = new ServerSocket(4444);
if(args.length > 0){
MyService = new ServerSocket(Integer.parseInt(args[0]));
}
}
catch(IOException e){
System.out.println("Couldn't linputten to port " + (args.length > 0 ? Integer.parseInt(args[0]) : 4444));
}
System.out.println("The server started. To stop it press <CTRL><C>.");
while(true){
try {
serviceSocket = MyService.accept();
new Thread(new Server()).start();
System.out.println("CREATED");
}
catch (IOException e) {
System.out.println("can't accept");
}
}
}
public void run(){
try {
input = new DataInputStream(serviceSocket.getInputStream());
output = new PrintStream(serviceSocket.getOutputStream());
while (true) {
line = input.readLine();
System.out.println("from client:" + line+"\n");
output.println("From server: " + line+"\n");
}
}
catch(IOException e) {
System.out.println(e);
}
}
}
主题。加入服务器缺失 –