淘先锋技术网

首页 1 2 3 4 5 6 7

TCP实现Client:

public class ClientDemo {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket s=new Socket(InetAddress.getByName("localhost"), 8888);
		OutputStream os=s.getOutputStream();
		FileInputStream fs=new FileInputStream(new File("文件路径"));
		byte[] bys=new byte[1024];
		fs.read(bys);
		os.write(bys,0,bys.length);
		os.close();
		s.close();
	}

}

TCP实现Server:

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

UDP实现Client

public class SenderDemo {
	public static void main(String[] args) throws IOException {
		DatagramSocket ds=new DatagramSocket();
		FileInputStream fs=new FileInputStream(new File("文件路径"));
			byte[] bys=new byte[1024];
					fs.read(bys);
			InetAddress address=InetAddress.getByName("SHANGJINGJING");
			DatagramPacket dp=new DatagramPacket(bys, bys.length, address, 8889);
		ds.send(dp);
		
		ds.close();
	}

UDP实现Server:

public class ReceiveDemo {
	public static void main(String[] args) throws IOException {
		DatagramSocket ds=new DatagramSocket(8889);
		byte[] bys=new byte[1024];
		int length=bys.length;
		DatagramPacket dp=new DatagramPacket(bys, length);
		ds.receive(dp);
		InetAddress address=dp.getAddress();
		byte[] data=dp.getData();
		int len=dp.getLength();
		System.out.println(address);
		System.out.println(new String(data,0,len));
		ds.close();
	}
}
}