套接字

建立链接流程

客户端:Socket socket1=new Socket("http://192.168.0.78",2016)

    前面的是服务器的ip地址,为了方便测试192.168.0.78即代表自己本机就是服务器,后面的服务器端口号,正常要使用1024~65535端口号

服务器端:ServerSocket serverSocket1=new ServerSocket(2016)

    表明这个服务器端套接字的端口号服务的是2016

然后     :Socket socket2=serverSocket1.accept()

    这个方法表明进程将会阻塞直到受到 链接

受到链接的客户端和服务器端都可以用DataInputStream和DataOutputStream来互通数据啦(首先服务器端要先开

DataInputStream in=new DataInputStream(socket1.getInputStream)

DataOutputStream out=new DataOutputStream(socket1.getOutputStream)

in.readUTF()

out.writeUTF()

客户端

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;

public class Test {
    public static void main(String args[]){
        String []mess={"hello1?","hello2","hello3"};
        DataInputStream in=null;
        DataOutputStream out=null;
        Socket socket1;
        try{
            socket1=new Socket("127.0.0.1",2016);
            in=new DataInputStream(socket1.getInputStream());
            out=new DataOutputStream(socket1.getOutputStream());
            for(int i=0;i<3;i++){
                out.writeUTF(mess[i]);
                String s=in.readUTF();
                System.out.println(s);
                Thread.sleep(1000);
            }
            
        }
        catch(Exception e){
            System.out.println("111");
            System.out.println(e.getMessage());
        }
    }
}

class ReadURL implements Runnable{
    private URL url;
    void seturl(URL a){
        url=a;
    }
    public void run(){
        try{
            InputStream in1=url.openStream();
            byte []b=new byte[1024];
            int n=-1;
            for(;(n=in1.read(b,0,1024))!=0;){
                String s=new String(b,0,n);
                System.out.print(s);
            }
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}
View Code

服务器端

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class test2{
    public static void main(String args[]){
        String []mess={"ok1","ok2","ok3"};
        DataInputStream in=null;
        DataOutputStream out=null;
        ServerSocket serverSocket1;
        Socket socket1;
        try{
            serverSocket1=new ServerSocket(2016);
            socket1=serverSocket1.accept();
            in=new DataInputStream(socket1.getInputStream());
            out=new DataOutputStream(socket1.getOutputStream());
            
            for(int i=0;i<3;i++){
                String s=in.readUTF();
                System.out.println(s);
                out.writeUTF(mess[i]);
                Thread.sleep(1000);
            }
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/vhyc/p/6092846.html