Java 中使用线程的套接字编程实现

Socket Programming Implementation Using Threading in Java

在这里我可以解决多个客户端和服务器之间的聊天应用程序的套接字编程,客户端可以向服务器发送多条消息。但是现在我想解决一个新问题,即在服务器的帮助下将来自任何客户端的任何字符串 [每个客户端最多可以发送 2 条消息] 转换为完整的大写字符串。服务器最多可以为 5 个客户端提供服务。

这是我的客户co.....

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        System.out.println("Client started..");
        Socket socket = new Socket("127.0.0.1", 22222);
        System.out.println("Client Connected..");

        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        while (true) {
            Scanner sc = new Scanner(System.in);

            String message = sc.nextLine();

            if(message.equals("exit")){
                break;
            }

            //sent to server...
            oos.writeObject(message);

            try {
                //receive from server..
                Object fromServer = ois.readObject();
                System.out.println("From Server: " + (String) fromServer);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        socket.close();

    }
}

这是我的服务器代码.......

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(22222);
        System.out.println("Server Started..");

        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("Client connected..");

            // new Server Thread Start.....
            new ServerThread(socket);


        }
    }
}

class ServerThread implements Runnable {

    Socket clientSocket;
    Thread t;

    ServerThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
        t = new Thread(this);
        t.start();
    }


    @Override
    public void run() {

        try {
            ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());

            while (true) {
                //read from client...
                Object cMsg = ois.readObject();
                if (cMsg == null)
                    break;
                System.out.println("From Client: " + (String) cMsg);

                String serverMsg = (String) cMsg;
                serverMsg = serverMsg.toUpperCase();

                //send to client..
                oos.writeObject(serverMsg);
            }

        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }

        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


//服务器端

package sockettreading;
 
import java.io.*;
import java.net.*;
 
/**
 *
 * @author Amanur Rahman
 */
public class SocketTreading {
 
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(5050);
        System.out.println("Server is starting...");
        int cn=1;
        while (cn<=5) {
            Socket s = ss.accept();
            System.out.println("Client"+cn+" is connected \n" + s);
            DataInputStream dis = new DataInputStream(s.getInputStream());
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            System.out.println("Assinging new thread for this client");
            Thread t = new ClientHandler(s, dis, dos);
            t.start();
            cn++;
        }
        System.out.println("Client limit cross");
        
        ss.close();
 
    }
}
 
class ClientHandler extends Thread {
 
    final Socket soc;
    final DataInputStream input;
    final DataOutputStream output;
    int i = 1;
 
    public ClientHandler(Socket s, DataInputStream dis,
            DataOutputStream dos) {
        this.soc = s;
        this.input = dis;
        this.output = dos;
    }
 
    @Override
    public void run() {
        String received;
        String ends;
        String toreturn;
        while (i <= 2) {
            try {
                output.writeUTF("Please write your message : ");
                String str = input.readUTF();
                System.out.println("Client msg is: "+ str.toUpperCase());
                output.writeUTF("Do you want to exit or continue ( if exit type \"ENDS\" ) ");
                ends = input.readUTF();
                if (ends.equals("ENDS")) {
                    System.out.println("Client" + this.soc + "send exit.");
                    this.soc.close();
                    System.out.println("Connection closed");
                    break;
                }
            } catch (IOException e) {
                System.out.println(e);
            }
            System.out.println("" + i);
            i++;
        }
 
        try {
            this.input.close();
            this.output.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

//客户端

package sockettreading;
 
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
 
/**
 *
 * @author Amanur Rahman
 */
public class ClientThreading {
 
    public static void main(String[] args) throws IOException {
        try(Socket s = new Socket("localhost", 5050);){
             System.out.println("Connected");
             Scanner scn = new Scanner(System.in);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());
        int i = 1;
        while (i <= 2) {
            System.out.println(dis.readUTF());
            String num1 = scn.nextLine();
            dos.writeUTF(num1);
 
            System.out.println(dis.readUTF());
            String num2 = scn.nextLine();
            dos.writeUTF(num2);
            System.out.println(dis.readUTF());
            String ends = scn.nextLine();
            dos.writeUTF(ends);
            if (ends.equals("ENDS")) {
                System.out.println("Closing the connection" + s);
                s.close();
                System.out.println("Connection closed");
                break;
            }
            i++;
        }
        System.out.println(dis.readUTF());
        s.close();
        dos.close();
        dis.close();
        }
        
        catch (IOException ex) {
            if(ex.getMessage()!=null){
                System.out.println("Already 5 clients are served so the server is closed: ");
            }else{
                System.out.println("Client 2 message already send. That's way the connection closed.");
            }
            
        }
 
       
    }
}