首页 > 代码库 > Java - TCP网络编程

Java - TCP网络编程

Java - TCP网络编程

Server

逻辑思路:

  1. 创建ServerSocket(port),然后服务器的socket就启动了
  2. 循环中调用accept(),此方法会堵塞程序,直到发现用户请求,返回用户的socket
  3. 利用多线程对用户socket进行IO操作

注意:对Scoket/File进行创建、关闭,都需要放try catch中,检测 IOException,所以将网络IO部分整体放入try catch中即可。

 

1. 字符串操作

输出:PrintWriter out=new PrintWriter(sock.getOutputStream(), true);

读取:BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()));

或者:Scanner input=new Scanner(sock.getInputStream());

 

2. 字节操作(一般用于传输文件,体积大,要求效率高,用BufferedInputStream/BufferedOutputStream)

输出:BufferedOutputStream out=new BufferedOutputStream(sock.getOutputStream());

输出:BufferedInputStream out=new BufferedInputStream(sock.getInputStream());

 

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

public class TCP_Server {
    
    public static void main(String[] args){
        
        int port=8888;
        
        try {
            ServerSocket sock=new ServerSocket(port);
            System.out.println("服务器启动,Port:"+sock.getLocalPort());
            while(true){
                Socket client=sock.accept(); //***注意,accept()是个阻塞函数,返回client socket***
                System.out.println("监测到TCP连接来自:"+client.getRemoteSocketAddress());
                new WorkThread(client).start(); //多线程
            }    
        } 
        catch (IOException e) {
            System.out.println("ERROR Found: "+e.getMessage());
        }
        //end try catch
    
        
    }
}


class WorkThread extends Thread{
    
    Socket sock;
    public WorkThread(Socket sock){
        this.sock=sock;
    }
    
    public void run(){
        try{
            //此处用BufferedReader实现
            BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintWriter out=new PrintWriter(sock.getOutputStream(),true);
            
            String s=null;
            while((s=in.readLine())!=null){ //断开会返回null
                if(s.equals("end"))
                    break;
                System.out.println("收到:"+s);
                out.println("Server:"+s);
            }
            
            /*注意,readLine()是个阻塞函数,放在while((s=readLine())!=null)中会堵塞程序,等待用户的数据。
             *有两种方式中断循环
             *1.用户端断开TCP程序,in.readLine()会返回null
             *2.用户正常退出,用户端发送个[结束标记]给服务器,服务器根据标记,中断循环
             */
            System.out.println("监测到TCP连接来自:"+sock.getRemoteSocketAddress()+"已断开。");
            
            in.close();
            out.close();
            sock.close();
        }
        catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
    
    
}

 

Client

逻辑思路:

  1. 创建Socket(IP, port),其参数为目标服务器的IP和port
  2. 然后就可以通过Socket进行IO操作了
import java.net.*;
import java.io.*;
import java.util.*;

public class TCP_Client {

    public static void main(String[] args) {
        
        Scanner in=new Scanner(System.in);
        
        try{
            
            int port=8888;
            String ip="127.0.0.1";
            
            Socket sock=new Socket(ip, port);
            
            //从socket中输出
            PrintWriter out=new PrintWriter(sock.getOutputStream(),true);
            //从socket中读取,此处用Scanner实现
            Scanner input=new Scanner(sock.getInputStream());
            
            while(true){
                System.out.print("请输入消息:");
                String s=in.nextLine();
                if(s.equals("end")){
                    out.println(s);
                    break;
                }
                
                out.println(s);
                System.out.println("发送:"+s);
                s=input.nextLine();
                System.out.println("收到:"+s);
            }
            
            in.close();
            input.close();
            out.close();
            sock.close();
        }
        catch (IOException e){
            System.out.println("ERROR Found: "+e.getMessage());
        }

    }

}

 

Java - TCP网络编程