基础---tcp/udp

网络通信三要素:IP,端口号,传输协议
第一步 ip,port封装成 InerAddress 
第二步 Socket 连接类;Packet打包类;

两种方式,

第一种UDP协议传输:

发送

package tu;

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

public class sss {		
public static void main(String []args) throws IOException  {
	DatagramSocket a=new DatagramSocket();
	String s="hello,im shazi";
	byte [] bys=s.getBytes();
	int length=bys.length;
	InetAddress add=InetAddress.getByName("192.168.0.102");

	DatagramPacket p=new DatagramPacket(bys,length,add,8888);
	a.send(p);

}
}

接受:

package tu;

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

public class Tree {
public static void main(String []args) throws IOException {
	
	DatagramSocket ad=new DatagramSocket(8888);
	byte[] a=new byte[1024];
	DatagramPacket p=new DatagramPacket(a,a.length);
	ad.receive(p);
	byte [] data=p.getData();
	System.out.println(new String(data));
	ad.close();
}
}

第二种方式:TCP协议

2.1 发送:

package tu;

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

import org.omg.CORBA.portable.OutputStream;

public class sss {		
public static void main(String []args) throws IOException  {
	Socket s=new Socket(InetAddress.getByName("192.168.0.102"),10086);
	java.io.OutputStream os= s.getOutputStream();
	String str="hello w s sahzi";
	os.write(str.getBytes());
	s.close();

}
}

socket.getOutputStream()源码

    public OutputStream getOutputStream() throws IOException {
       ...验证
        final Socket s = this;
        OutputStream os = null;
        try {
            os = AccessController.doPrivileged(
                new PrivilegedExceptionAction<OutputStream>() {
                    public OutputStream run() throws IOException {
                        return impl.getOutputStream(); //【入】
                    }
                });
        } catch (java.security.PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
        return os;
    }
    protected synchronized OutputStream getOutputStream() throws IOException {
        synchronized (fdLock) {
            if (isClosedOrPending())
                throw new IOException("Socket Closed");
            if (shut_wr)
                throw new IOException("Socket output is shutdown");
            if (socketOutputStream == null)
                socketOutputStream = new SocketOutputStream(this); //【就是new了一个】
        }
        return socketOutputStream;
    }

看outputStream.write()源码

    public void write(byte b[]) throws IOException {
        socketWrite(b, 0, b.length);
    }
//跟进
    private void socketWrite(byte b[], int off, int len) throws IOException {
... 检测
        FileDescriptor fd = impl.acquireFD();
        try {
            socketWrite0(fd, b, off, len);
        } catch (...
        } finally {
            impl.releaseFD();
        }
    }
//跟进  native方法!
    private native void socketWrite0(FileDescriptor fd, byte[] b, int off,
                                     int len) throws IOException;

2.2 接受:

package tu;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;

public class Tree {
public static void main(String []args) throws IOException {
	ServerSocket a11=new ServerSocket(10086);
	Socket s=a11.accept();
	InputStream is=s.getInputStream();
	byte []bys=new byte[1024];
	int len;
	len=is.read(bys);
	System.out.println(new String(bys,0,len));
	s.close();
	is.close();
	a11.close();
	
}
}

总结:

三,缓冲流版本

服务端: 进行监听。设置监听端口为8888,使用accept()方法进行监听。

public class Server {
	public static void main(String []args) {
		final int port=8888;
		ServerSocket serverSocket=null;
		try {
			//给服务器监听 绑定端口
			serverSocket=new ServerSocket(port);
			System.out.println("启动服务器,监听端口为:"+port);
			while(true) {
				System.out.println("监听中:");
				//收到 请求。
				Socket socket=serverSocket.accept();
				System.out.println("客户端["+socket.getPort()+" ] 已连接");
				//开始读出数据
				BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
				
				String msg=reader.readLine();
				if(msg!=null) {
					System.out.println("客户端["+socket.getPort()+" ] : "+msg);
					//回复 客户 发送的信息
					writer.write("服务区"+msg+"\n");
					writer.flush();
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(serverSocket!=null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

客户端:设置服务端的ip地址和port端,在new Socket()的时候,就开始建立连接了。Socket把自己的ip和分配的port也封装进去,让服务端可以使用该信息进行回复。

public class Client {
	public static void main(String []args) throws IOException {
	final String host="127.0.0.1";
	final int port=8888;
	Socket socket=null;
	BufferedWriter writer=null;
	
	try {
		while(true){
		socket=new Socket(host,port);
		BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		 writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		//等待用户的输入
		
		BufferedReader consoleReader=new BufferedReader(new InputStreamReader(System.in));
		String input=consoleReader.readLine();
		writer.write(input+"\n");
		writer.flush();
		
		//读取服务器的回复
		String msg=reader.readLine();
		System.out.println(msg);
		if(msg.equals("no"))
			break;
		 }
	}catch(Exception e) {
		e.printStackTrace();
	}finally {
		System.out.print("客户端关闭");
		if(writer!=null) {
			writer.close();
		}
	}
}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值