TCP socket连接小试

服务端和客户端的交互图示:

 

数据通过服务端和客户端输入和输出的流来建立联系,一个输入,另一个就输出,一个输出,另一个就输入

 

通信过程:


先启动 Server 端,进入一个死循环以便一直监听某端口是否有连接请求。然后运行 Client
端,客户端发出连接请求,服务端监听到这次请求后向客户端发回接受消息,连接建立,启动一个线程
去处理这次请求,然后继续死循环监听其他请求。客户端输入字符串后按回车键,向服务器发送数据。
服务器读取数据后回复客户端数据。这次请求处理完毕,启动的线程没有消亡(因为循环输入的)。如果客户端接收到 "EXIT" 之
外的返回数据,会再次发送连接请求并发送数据,还是这个线程在工作,服务端继续响应。当客户端接受到“EXIT”时,启动的线程消亡,客户端结束
。。直到当客户端接收到的返回数据为 "EXIT" 时,客户端退出且关闭。当再次启动一个客户端,cnt+1(这里并不是根据ip辨别客户端数量,每次客户端的启动消亡就会+1)

还有这个程序的一种写法参考:http://blog.csdn.net/defonds/article/details/7971259

TcpServer.java:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class TcpServer {
    public static void main(String[] args) {
        int port;
        ServerSocket server_sSocket;
        BufferedReader input;
        try {
            port = Integer.parseInt(args[0]);
        } catch (Exception e) {
            System.out.println("port = 1500(默认)");
            port = 1500;
        }
        
        try {
            server_sSocket = new ServerSocket(port);
            System.out.println("服务端等待客户端信息在端口" + server_sSocket.getLocalPort());
            
            int cnt = 0;
            while(true) {
                Socket socket = server_sSocket.accept();
                cnt++;
                new tcpServerThread(socket,cnt).start();
                System.out.println("新客户端被接受" + socket.getInetAddress() + ":" + socket.getPort());
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

class tcpServerThread extends Thread {
    private Socket tcpSocket;
    private int intNumber;
    public tcpServerThread(Socket socket, int cnt) {
        tcpSocket = socket;
        intNumber = cnt;
    }
    public void run() {
        try {
       //获得输入流,对应客户端输出流 BufferedReader inReader
= new BufferedReader(new InputStreamReader(tcpSocket.getInputStream() )); PrintWriter out = new PrintWriter(tcpSocket.getOutputStream(),true); out.println("你的编号是" + intNumber + "可以输入EXIT退出程序"); String in = ""; in = inReader.readLine(); while(!in.trim().equals("EXIT")) { out.println("显示(" + intNumber + "):" + in + tcpSocket.getLocalPort()); in = inReader.readLine(); } out.println("再见客户端(" + intNumber + ")"); tcpSocket.close(); System.out.println("客户端(" + intNumber + ")被关闭"); } catch (Exception e) { System.out.println(e); } } }

TcpClient.java:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;


public class TcpClient {
    public static void main(String[] args) {
        String server = "localhost";
        int port = 1500;
        System.out.println("server=" + server + " port= " + port);
        try {
            System.out.println("正在连接  " + server);
            
            //通过端口号建立连接
            Socket tcpSocket = new Socket(server,port);
            
            //获得输出流,与服务端输入流对应
            PrintStream out = new PrintStream(tcpSocket.getOutputStream());
            
            
            BufferedReader in = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
            System.out.println(in.readLine());
            System.out.println("请输入");
            
            BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
            String line = userInput.readLine();
            while(!line.trim().equals("EXIT")) {
                    out.println(line.trim());
                    System.out.println(in.readLine());
                    line = userInput.readLine();
            }
            out.println(line.trim());
            out.close();
            in.close();
            System.out.println("关闭连接.");
            tcpSocket.close();
        
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
    }
}

 关于设计的类和异常,这篇博客讲的详细一点:

http://www.cnblogs.com/rond/p/3565113.html

 

posted @ 2017-06-27 11:24  Lawliet__zmz  阅读(194)  评论(0编辑  收藏  举报