当前位置:网站首页>Introduction to socket UDP and TCP
Introduction to socket UDP and TCP
2022-06-25 11:05:00 【Anonymous & Xiaoyu】
List of articles
Socket UDP、TCP brief introduction
1.1 Java obtain IP、URL
// obtain IP
public class IPDemo {
public static void main(String[] args) throws UnknownHostException {
// Access to the local IP: Host name / 127.0.0.1 / localhost
InetAddress ip=InetAddress.getByName("gudu");
System.out.println(ip);
System.out.println(ip.getHostAddress()); // return IP
System.out.println(ip.getHostName()); // Return computer name
System.out.println(ip.getLocalHost()); // Get the local host IP
System.out.println("----------------------- Get network IP------------------------");
InetAddress baiduIP=InetAddress.getByName("www.baidu.com");
System.out.println(baiduIP);
}
}
// obtain url
public class URLDemo {
public static void main(String[] args){
InputStream in=null;
OutputStream out=null;
// Given a URL Address
try {
URL url=new URL("");
// Establish a channel
URLConnection conn=url.openConnection();
// adopt URLConnection Object get object stream
in=conn.getInputStream();
File file =new File("D:URL");
if(!file.exists()){
file.mkdirs();// Create folder
}
out=new FileOutputStream(file.getPath()+"/"+"pag.png");
byte[] buf=new byte[1024];
int len =-1;
System.out.println(" Download start ........");
while(-1!=(len=in.read(buf))){
out.write(buf, 0, len);
}
System.out.println(" Download successful ........");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.2 UDP Server side \ client
// establish UDP The receiving end of
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
//1. establish UDP Socket Receiver object (DatagramSocket), Because you want to receive the database , So specify a port
DatagramSocket ds =new DatagramSocket(10003);
System.out.println(" Receiver start .........");
//2. Create datagram packet object ( DatagramPacket )
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
//3. Use receive() Method accepts datagram packets
ds.receive(dp);// Blocking
//4. Get information through the method of datagram package object
byte[] data=dp.getData(); // Get the data sent
InetAddress ip=dp.getAddress(); // Get the IP
int port=dp.getPort(); // Get the port number of the sender
System.out.println(ip+" Said the "+new String(data,0,dp.getLength()));
ds.close(); // Closed flow
}
}
/** * Byte array +Data Input stream * @param data * @return * @throws IOException */
public static double convert(byte[] data) throws IOException{
DataInputStream dis =new DataInputStream(new ByteArrayInputStream(data));
double num =dis.readDouble(); // The next eight bytes of this input stream , Interpret them as a double
dis.close();
return num;
}
// establish UDP The sender of
public class SendDemo {
public static void main(String[] args) throws IOException {
//1. establish UDP Of DatagramSocket object , Indicate the external port number
DatagramSocket ds=new DatagramSocket(10002);
System.out.println(" Sender start ........");
//2. adopt DatagramPacket Object to package
byte[] buf=" test , I love you! ".getBytes();
DatagramPacket dp=new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"),10003);
//3. adopt DatagramSocket Of send() , Send the datagram packet to the specified receiving end
ds.send(dp);
ds.close();
}
}
/** * Byte array data source +Data Output stream * @param num * @return * @throws IOException */
public static byte[] convert(double num) throws IOException{
byte[] data =null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos =new DataOutputStream(bos);
dos.writeDouble(num); // Will a double Value is written to the output stream
dos.flush();
// get data
data = bos.toByteArray();
// Create a new assigned byte Array whose size is the current size of this output stream , And the valid contents of the buffer have been copied to the array .
dos.close();
return data;
}
}
1.3 TCP Server side / client
//TCP Protocol transfer : Establishment of server side
/** step * 1. establish TCP Server side objects (ServerSocket) * 2. call accept() Method to get the... Of the client brought by the connection Socket object * 3. Through the client Scoket Object acquisition IO Stream to read data * 4. */
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(10001);
Socket client=null;
InputStream in=null;
System.out.println(" Server startup ........");
boolean b=true;
while(b){
client=server.accept( ); // Listen and accept connections to this socket
in=client.getInputStream(); // Returns the input stream for this socket .
byte[] buf=new byte[1024];
int len=in.read(buf);
InetAddress ip=client.getInetAddress();
System.out.println(ip+" say "+new String(buf,0,len));
}
server.close();
client.close();
}
}
//TCP Protocol transfer : The establishment of the client
/** step * 1. establish TCP Client object (Socket) * 2. If the connection to the server is successful , adopt Socket Object acquisition IO flow * 3. Use IO flow , Data operation * 4. close resource */
public class ClientDemo {
public static void main(String[] args) throws IOException {
Socket client=new Socket("127.0.0.1",10001);
OutputStream out=client.getOutputStream();
out.write(" Hello Server".getBytes());
client.close();
}
}
边栏推荐
- Array structure collation
- Sign up to open the third session of the "flying oar hacker marathon". It's been a long time
- 金仓数据库 KingbaseES 插件force_view
- Performance memory
- 手机办理广州证券开户靠谱安全吗?
- 每日3题(3)-检查整数及其两倍数是否存在
- 报名开启|飞桨黑客马拉松第三期如约而至,久等啦
- WPF binding expression and binding data source (I)
- 【观察】ObjectScale:重新定义下一代对象存储,戴尔科技的重构与创新
- Google Earth Engine(GEE)——evaluate實現一鍵批量下載研究區內的所有單張影像(上海市部分區域)
猜你喜欢
![[paper reading | deep reading] drne:deep recursive network embedding with regular equivalence](/img/48/4e8d367b49f04a2a71a2c97019501f.png)
[paper reading | deep reading] drne:deep recursive network embedding with regular equivalence

Sign up to open the third session of the "flying oar hacker marathon". It's been a long time

Previous string inversion topic

ES 学习

CSRF attack

FPGA displays characters and pictures based on VGA

Complete steps for a complete Oracle uninstall

一个五年北漂的技术er,根据这些年的真实经历,给应届生的一些建议

无心剑中译伊玛·拉扎罗斯《新巨人·自由女神》

MCU development -- face recognition application based on esp32-cam
随机推荐
QT: parsing JSON
持续交付-Jenkinsfile 语法
Android之Kotlin语法详解与使用
Opencv learning (I) -- environment building
之前字符串反转的题目
Output reading: apply what you have learned
龙书虎书鲸书啃不动?试试豆瓣评分9.5的猴书
金仓数据库 KingbaseES 插件force_view
Simple use of SVN
ZABBIX distributed system monitoring
Is it safe to speculate in stocks by mobile phone?
XSS攻击
COSCon'22 讲师征集令
Garbage collection mechanism
Network remote access using raspberry pie
[the path of system analyst] Chapter 6: Double inventory demand engineering (comprehensive knowledge concept)
无心剑中译伊玛·拉扎罗斯《新巨人·自由女神》
中国信通院沈滢:字体开源协议——OFL V1.1介绍及合规要点分析
keep-alive
Cdn+cos ultra detailed steps for drawing bed construction