JavaTCP通信

Server为服务器,Receive为客户端,先运行服务器,再运行客户端


Receive

package Java.TCP;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import java.util.Scanner;

public class Receive {
    public static void main(String[] args){
        byte[] addr=new byte[]{127,0,0,1};
        try{
            InetAddress local=InetAddress.getByAddress(addr);
            Socket s=new Socket(local,3762);

            System.out.println("链接成功");
            OutputStream out=s.getOutputStream();
            System.out.println("输出流链接成功");
            PrintWriter pw=new PrintWriter(out);
            System.out.println("输出准备完毕");
            Scanner scan = new Scanner(System.in);
            while (true) {
                String send = scan.nextLine();
                if (send.length() > 0) {
                    pw.write("**********" + send + "**********" + "\r\n");
                    pw.flush();
                }
            }
        }
        catch(UnknownHostException e){
            System.out.println("无法找到相应机器:"+e.getMessage());
        }
        catch(IOException e){
            System.out.println("数据传输出现异常:"+e.getMessage());
        }
    }
}


Server

package Java.TCP;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import java.util.Scanner;

public class Receive {
    public static void main(String[] args){
        byte[] addr=new byte[]{127,0,0,1};
        try{
            InetAddress local=InetAddress.getByAddress(addr);
            Socket s=new Socket(local,3762);

            System.out.println("链接成功");
            OutputStream out=s.getOutputStream();
            System.out.println("输出流链接成功");
            PrintWriter pw=new PrintWriter(out);
            System.out.println("输出准备完毕");
            Scanner scan = new Scanner(System.in);
            while (true) {
                String send = scan.nextLine();
                if (send.length() > 0) {
                    pw.write("**********" + send + "**********" + "\r\n");
                    pw.flush();
                }
            }
        }
        catch(UnknownHostException e){
            System.out.println("无法找到相应机器:"+e.getMessage());
        }
        catch(IOException e){
            System.out.println("数据传输出现异常:"+e.getMessage());
        }
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页