使用java实现Server和Client(TCP)

Server.java

import java.io.*;
import java.net.*;


public class Server {

    public static final int PORT=8888;
    
    public void Server() throws IOException {
        ServerSocket ss = new ServerSocket(PORT);
        InetAddress ia = InetAddress.getByName(null);

        System.out.println("Server@"+ia+" start!");

        try{
            while(true){
                Socket s = ss.accept();// listen PORT;
                try{
                    new ServerOne(s);
                } catch (IOException e) {
                    s.close();
                } 
            }
        }finally{
            ss.close();
            System.out.println("Server stop!");
        }
    }
}

class ServerOne extends Thread {
    private Socket s;
    private BufferedReader in;
    private PrintWriter out;
    public ServerOne(Socket s) throws IOException {
        this.s = s;
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(new BufferedWriter
                (new OutputStreamWriter(s.getOutputStream())), true);
        start();
    }
    public void run(){
        try {
            while(true) {
                String str = in.readLine();
                if(str.equals("end")) break;
                System.out.println("Server: receive information"+str);
                out.println("Echo: "+str);
            }
            System.out.println("closing....");
        } catch (IOException e){
        } finally {
            try{
                s.close();
            }catch(IOException e){}
        }
    }
}

Client.java:

import java.io.*;
import java.net.*;

public class Client extends Thread {
    static final int MAX_THREADS=25;
    private static int id = 0;
    private static int threadCount = 0;
    private Socket s;
    private BufferedReader in;
    private PrintWriter out;

    public static int getThreadCount(){
        return threadCount;
    }

    public Client(InetAddress ia){
        threadCount++;
        id++;
        System.out.println("Making client: " + id);
        try{
            s = new Socket(ia, Server.PORT);
        } catch (IOException e) {}
        try{
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new PrintWriter(new BufferedWriter
                    (new OutputStreamWriter(s.getOutputStream())), true);
            start();
        }catch(IOException e1){
            try{
                s.close();
            }catch(IOException e2){
                System.out.println("Error in Client\n");
            }
        }

    }

    public void run() {
        try{
            String str;
            for(int i = 0; i < 5; i++) {
                out.println("Client #"+id+":"+i);
                str=in.readLine();
                System.out.println("Client: send message#"+id+":"+i+"\n"
                        +"Server reply: "+str);
            }
            out.println("end");
        }catch(IOException e){
        }finally{
            try {
                s.close();
            } catch (IOException e){}
        }
    }

    public static void main(String args[]) throws IOException, InterruptedException {
        InetAddress ia = InetAddress.getByName(null); //null mean localhost
        while(true){
            if(getThreadCount() < MAX_THREADS)
                new Client(ia);
            else break;
            Thread.currentThread().sleep(10);
        }
    }
}


Java实现TCP ServerTCP Client可以使用Java提供的Socket类和ServerSocket类。 下面是一个简单的TCP Server实现: ```java import java.net.*; import java.io.*; public class TCPServer { public static void main (String [] args ) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9999); } catch (IOException e) { System.err.println("Could not listen on port: 9999."); System.exit(1); } Socket clientSocket = null; System.out.println ("Waiting for connection....."); try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } System.out.println ("Connection successful"); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println ("Server: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } } ``` 上述代码创建了一个ServerSocket并监听9999端口。当客户端连接后,程序会创建一个Socket并开始读取客户端发送的数据。服务器将客户端发送的数据原样返回,并在客户端发送“Bye.”后关闭连接。 下面是一个简单的TCP Client实现: ```java import java.net.*; import java.io.*; public class TCPClient { public static void main(String[] args) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("localhost", 9999); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("Server: " + in.readLine()); if (userInput.equals("Bye.")) break; } out.close(); in.close(); stdIn.close(); socket.close(); } } ``` 上述代码创建了一个Socket并连接到服务器的9999端口。客户端从标准输入读取数据,并将其发送到服务器。客户端接收服务器发送的数据,并将其打印到控制台。 这只是一个简单的示例,实际应用中需要考虑更多的异常情况和数据处理方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值