java udp与tcp
一:基础 NET基本对象java.net.InetAddress类的使用
IP地址是IP使用的32位(IPv4)或者128位(IPv6)位无符号数字,它是传输层协议TCP,UDP的基础。InetAddress是Java 对IP地址的封装,在java.net中有许多类都使用到了InetAddress,包括 ServerSocket,Socket,DatagramSocket等等。
InetAddress的实例对象包含以数字形式保存的
IP地址,同时还可能包含主机名(如果使用主机名来获取InetAddress的实例,或者使用数字来构造,并且启用了反向主机名解析的功能)。
InetAddress类提供了将主机名解析为IP地址(或反之)的方法。
InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取,有以下的方法:
static InetAddress[] getAllByName(String host)
static InetAddress getByAddress(byte[] addr)
static InetAddress getByAddress(String host,byte[] addr)
static InetAddress getByName(String host)
static InetAddress getLocalHost()
实例代码:
import java.net.InetAddress;
import java.net.UnknownHostException; public class Demo { /**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException { //获取本地主机的IP地址对象
//InetAddress inet = InetAddress.getLocalHost(); //获取任意一台主机的IP地址对象
InetAddress inet = InetAddress.getByName("10.2.156.26"); //获取本地主机的ip地址
String ip = inet.getHostAddress(); //获取本机主机的主机名
String name = inet.getHostName(); System.out.println(ip+":"+name);
} }
二:udp相关代码
1:使用udp协议实现数据的发送
1:创建Socket发送端
2:明确要发送的数据
3:把要发送的数据封装成数据报包
4:使用Socket的发送功能发送数据
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException; public class Send1 { /**
* 使用udp协议实现数据的发送
* 1:创建Socket发送端
* 2:明确要发送的数据
* 3:把要发送的数据封装成数据报包
* 4:使用Socket的发送功能发送数据
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("发送方启动......");
//1:创建Socket发送端---确定了使用的协议
DatagramSocket ds = new DatagramSocket(); //2:明确要发送的数据
String data = "明天放假";
byte[] b = data.getBytes();
//3:把要发送的数据封装成数据报包
//数据报包中包含了要发送的数据,接收数据的主机的IP地址对象,以及接收方使用哪个端口来接收
DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("10.2.156.15"),22222); //4:使用Socket的发送功能发送数据
//该方法内部使用的输出流,向网络上的另一台主机输出数据
ds.send(dp); ds.close();
} }
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException; public class Receive1 { /**
* 使用udp协议实现数据的接收
* 1:创建Socket端点,同时要监听一个端口
* 2:创建用来接收数据的数据报包
* 3:使用Socket的接收功能来接收数据
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("接收方启动......");
//1:创建Socket端点
DatagramSocket ds = new DatagramSocket(22222); //2:创建一个空的数据报包来接收发送过来的数据报包
byte[] arr = new byte[1024];
DatagramPacket dp = new DatagramPacket(arr, arr.length); //使用Socket的接收功能来接收数据
ds.receive(dp); //解析数据
//获取发送过来的数据
byte[] data = dp.getData();
String shuju = new String(data,0,dp.getLength()); //获取发送方的ip地址
String ip = dp.getAddress().getHostAddress(); //获取发送方发送数据使用的端口
int port = dp.getPort(); System.out.println(ip+":"+port+":"+shuju); } }
2:使用udp实现可以一直接收数据
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class Send2
{
public static void main(String[] args) throws IOException
{
DatagramSocket ds = new DatagramSocket(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null;
while ((line = br.readLine()) != null)
{
DatagramPacket dp = new DatagramPacket(line.getBytes(),
line.length(), InetAddress.getByName("10.2.156.26"), 10001); ds.send(dp);
if ("over".equals(line))
{
System.out.println("程序结束!");
break;
}
}
ds.close();
br.close();
}
}
Send
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException; public class Receive2 { /**
* 使用udp实现可以一直接收数据
* @throws IOException
*/
public static void main(String[] args) throws IOException { System.out.println("接收方启动.....");
// 创建Socket端点,同时监听一个端口
DatagramSocket ds = new DatagramSocket(33333); while(true)
{
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length); ds.receive(dp); String data = new String(dp.getData(),0,dp.getLength());
String ip = dp.getAddress().getHostAddress();
System.out.println(ip+":"+data);
}
//ds.close(); } }
Receive
3:使用udp实现既能发送也能接收---聊天程序
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException; public class UdpChat { /**
* 使用udp实现既能发送也能接收---聊天程序
* 发送的同时还能接收,使用多线程
* 创建一个线程负责发送
* 创建一个线程负责接收
* @throws SocketException
*/
public static void main(String[] args) throws SocketException {
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receiveSocket = new DatagramSocket(44444); new Thread(new Send(sendSocket)).start();
new Thread(new Receive(receiveSocket)).start();
} }
//描述接收任务
class Receive implements Runnable
{
private DatagramSocket socket;
public Receive(DatagramSocket socket)
{
this.socket = socket;
}
@Override
public void run() { while(true)
{
byte[] buf= new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length); try {
socket.receive(dp); String data = new String(dp.getData(),0,dp.getLength());
String ip = dp.getAddress().getHostAddress();
if("baibai".equals(data))
{
System.out.println(ip+"离开了,不聊了");
}
System.out.println(ip+":"+data); } catch (IOException e) {
e.printStackTrace();
}
} } }
//描述发送任务
class Send implements Runnable
{
private DatagramSocket socket;
public Send(DatagramSocket socket)
{
this.socket = socket;
} @Override
public void run() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
while((line = br.readLine())!=null)
{
byte[] b = line.getBytes();
DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("10.2.156.255"),44444);
socket.send(dp);
if("baibai".equals(line))
{
break;
}
}
br.close();
socket.close(); } catch (IOException e) {
e.printStackTrace();
}
}
}
Chat
三:tcp相关代码
1:使用Tcp实现数据的发送(在服务器端把字符串变成大写返回到客户端)
代码:
package tcp; //172.17.9.1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException; /**
* 使用Tcp实现数据的发送
* 1:创建Socket端点,同时指明连接的服务器的Ip地址和端口
* 2:从 Socket流中获取输出流
* 3:使用输出流向服务器端写入数据
*
* @throws IOException
* @throws UnknownHostException
*/
public class Client {
public static void main(String[] args) throws IOException {
// 创建Tcp协议的客户端,同时指明连接的服务器的Ip地址和端口
// 如果这条语句执行成功,不但创建了一个客户端对象,同时也和服务器端连接成功
// 如果连接成功,说明和服务器端建立了一条通道
// 这条通道就是Socket流(也就是客户端对象),Socket流中既有字节输入流,也有字节输出流
Socket s = new Socket(InetAddress.getByName("172.17.9.1"), 8888); //创建读取键盘输入的数据的字符读取流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//创建发送小写字符串到服务器端的字符输出流
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os, true);
//创建接收服务器返回的大写字符串的字符读取流
InputStream is = s.getInputStream();
BufferedReader brr = new BufferedReader(new InputStreamReader(is));
//读取键盘输入的字符串并发给服务器端,并接收大写字符串
while (true) {
String line = null;
if ((line = br.readLine()) != null) {
if ("over".equals(line)) {
System.out.println("程序结束!!");
break;
}
ps.println(line);//发送小写字符串到服务器端 String str = brr.readLine();//接收服务器返回的大写字符串
System.out.println(str);
}
}
brr.close();
ps.close();
br.close();
s.close(); }
}
Client
package tcp; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
*使用Tcp实现数据的接收
*1:创建Socket端点,同时监听一个端口
*2:获取客户端对象,也就是获取Socket对象,也就是获取流对象,从而和客户端使用同一个流
*3:从Socket流中获取输入流
*4:使用输入流读取客户端发送的数据
* @throws IOException
*/
public class Server {
public static void main(String[] args) throws IOException {
//1:创建Socket端点,同时监听一个端口
ServerSocket ss = new ServerSocket(8888);
//获取客户端对象
Socket s = ss.accept();
//创建接收小写字符串的字符读取流
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//创建发送大写字符串的字符输出流
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
//循环读取客户端,再发送大写字符串到客户端
while (true) {
String line = br.readLine();
if ("over".equals(line))
break;
else
pw.println(line.toUpperCase());
}
pw.close();
br.close();
s.close();
ss.close();
}
}
Server
2:实现文本文件的上传:上传完成时,服务器端返回"上传成功"
package tcp; import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 实现文本文件的上传:上传完成时,服务器端返回"上传成功"
* 客户端:
* 1:读取本地的一个文件
* 2:发送到服务器端
* 3:接收服务器端返回的"上传成功"
* @throws IOException
* @throws UnknownHostException
*/
public class Client2 { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket(InetAddress.getByName("172.17.9.1"), 9999);
//创建读取文本文件的字符读取流
BufferedReader br = new BufferedReader(new FileReader(
"tempFile\\Demo.java"));
//创建发送到服务器端的字符输出流
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
//创建接收服务器端返回的"上传成功"的字符读取流
InputStream is = s.getInputStream();
BufferedReader brr = new BufferedReader(new InputStreamReader(is)); String line = null;
//循环读取文件并写入到服务器端
while ((line = br.readLine()) != null) {
pw.println(line);
}
//向服务器端发送结束标记
s.shutdownOutput();//向服务器发送结束标记==》结束的是输出
//接收服务器端返回的"上传成功"
String res = brr.readLine();
System.out.println(res);
br.close();
s.close();
} }
Client2
package tcp; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket; /**
* 实现文本文件的上传:上传完成时,服务器端返回"上传成功"
* 服务器端:
* 1:接收客户端发送的数据
* 2:写入到一个本地文件
* 3:发送“上传成功”
* @throws IOException
*/ public class Server2 { public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9999);
//获取客户端对象
Socket s = ss.accept();
//创建接收客户端发送的数据的字符读取流
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//创建写入到一个本地文件的字符输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("tempFile\\Demo_copy.java"));
//创建发送“上传成功”的字符输出流
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
//循环读取客户端发送的数据,写入到本地文件
String line = null;
//读取的是客户端,所以读不到 null
while((line = br.readLine())!=null)
{
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
//发送“上传成功”
pw.println("上传成功!!");//这里如果用户println,它会自动刷新,如果是write 他不会自动刷新 s.close();
ss.close(); } }
Server2
3:实现图片的上传
package tcp; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 实现图片的上传
* @throws IOException
* @throws UnknownHostException
*/
public class client3 { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket(InetAddress.getByName("172.17.9.1"),6666);
//读取图片的字节读取流
FileInputStream fis = new FileInputStream("img\\img.jpg");
//发送到服务器端的字节输出流
OutputStream os = s.getOutputStream();
//读取上传成功的字节读取流
InputStream is = s.getInputStream();
//循环读取文件,并发送到服务器端
byte[] b = new byte[1024];
int len = 0;
while((len = fis.read(b))!=-1)//==》读取字节的时候,返回的是int即读到的个数,参数为字符数组的引用
{
os.write(b,0,len);
} //向服务器端写入结束标记
s.shutdownOutput();
//读取上传成功
byte[] arr = new byte[1024];
int num = is.read(arr);
System.out.println(new String(arr,0,num));
s.close(); } }
client3
package tcp; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; public class Server3 { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); FileOutputStream fos = new FileOutputStream("img\\img_copy.jpg"); byte[] b = new byte[1024];
int num = 0;
while((num = is.read(b))!=-1)
{
fos.write(b,0,num);
} String str = "上传成功!";
os.write(str.getBytes());
os.flush(); s.close();
ss.close();
} }
Server3
4:实现图片的同步上传
package tcp; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException; public class client4 { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket(InetAddress.getByName("172.17.9.1"),6666); FileInputStream fis = new FileInputStream("img\\img.jpg"); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); byte[] b = new byte[1024];
int len = 0;
while((len = fis.read(b))!=-1)
{
os.write(b,0,len);
}
byte[] arr = new byte[1024];
s.shutdownOutput(); int num = is.read(arr);
System.out.println(new String(arr,0,num));
s.close(); } }
client4
package PicUpload; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket; public class PicUpload implements Runnable { Socket s; public PicUpload(Socket s) {
this.s = s;
} @Override
public void run() { String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "连接到服务器..");
try {
// 防止文件覆盖
int num = 0;
File dir = new File("E:\\Image");
if (!dir.exists())
dir.mkdir();
File file = new File(dir, ip + "(" + (++num) + ")" + ".jpg");
while (file.exists())
file = new File(dir, ip + "(" + (++num) + ")" + ".jpg");
OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
} String str = "上传成功!";
os.write(str.getBytes());
os.flush(); s.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
PicUpload
package tcp; import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; import PicUpload.PicUpload; public class Server4 { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666);
while(true)
{
Socket s = ss.accept();
new Thread(new PicUpload(s)).start();
} } }
Server4
java udp与tcp的更多相关文章
- Java UDP和TCP的区别
为什么要写这篇博客:是这样的,最近听朋友说,有不少公司面试的时候会问道TCP和UDp的却别,所以就写出一篇简单的来描述他们之间的区别,送给那些即将面试的朋友们. UDP: 1.UDP, a.将数据以及 ...
- JAVA基础学习day24--Socket基础一UDP与TCP的基本使用
一.网络模型 1.1.OIS参考模型 1.2.TCP/IP参考模型 1.3.网络通讯要素 IP地址:IPV4/IPV6 端口号:0-65535,一般0-1024,都被系统占用,mysql:3306,o ...
- java 网络编程-tcp/udp
--转自:http://blog.csdn.net/nyzhl/article/details/1705039 直接把代码写在这里,解释看这里吧:http://blog.csdn.net/nyzhl/ ...
- Java中的TCP/UDP网络通信编程
127.0.0.1是回路地址,用于测试,相当于localhost本机地址,没有网卡,不设DNS都可以访问. 端口地址在0~65535之间,其中0~1023之间的端口是用于一些知名的网络服务和应用,用户 ...
- java学习之tcp与udp的实现
package com.gh.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...
- Java网络通信协议、UDP、TCP类加载整理
网络通信协议 网络通信协议 网络通信协议有很多种,目前应用最广泛的是TCP/IP协议(Transmission Control Protocal/Internet Protoal传输控制协议/英特网互 ...
- Java第三阶段学习(八:网络通信协议、UDP与TCP协议)
一.网络通信协议 1.概念: 通过计算机网络可以使多台计算机实现连接,位于同一个网络中的计算机在进行连接和通信时需要遵守一定的规则,在计算机网络中,这些连接和通信的规则被称为网络通信协议,它对数据的传 ...
- 牛客网Java刷题知识点之TCP、UDP、TCP和UDP的区别、socket、TCP编程的客户端一般步骤、TCP编程的服务器端一般步骤、UDP编程的客户端一般步骤、UDP编程的服务器端一般步骤
福利 => 每天都推送 欢迎大家,关注微信扫码并加入我的4个微信公众号: 大数据躺过的坑 Java从入门到架构师 人工智能躺过的坑 Java全栈大联盟 ...
- Java之网络编程UDP和TCP
注*部分转来的 第1章 网络通信协议 通过计算机网络可以使多台计算机实现连接,位于同一个网络中的计算机在进行连接和通信时需要遵守一定的规则,这就好比在道路中行驶的汽车一定要遵守交通规则一样.在计算机网 ...
随机推荐
- 关于MVC4.0中@Styles.Render用法与详解
本文分享于http://keleyi.com/a/bjac/q74dybjc.htm文章,感觉写的蛮好所以就拿过来做笔记了,希望对大家有帮助 最近公司的新项目用了MVC 4.0,接下来一步步把 工作中 ...
- css线性渐变--linear-gradient
使用css直接写渐变,对于现在而言,应该属于比价简单的一件事了,在一定程度上,扁平化的设计趋势的出现,减少了使用渐变色的场景,但是并不影响我们逐渐的熟悉线性渐变Linear-gradient的写法. ...
- 静态工厂方法VS构造器
我之前已经介绍过关于构建者模式(Builder Pattern)的一些内容,它是一种很有用的模式用于实例化包含几个属性(可选的)的类,带来的好处是更容易读.写及维护客户端代码.今天,我将继续介绍对象创 ...
- 《javascript高级程序设计》第三章学习笔记
Undefined类型 该类型只有一个值,即undefined. 对未初始化的变量和未定义的变量,用typeof检测,都会返回'undefined' Null类型 该类型只有一个值,null.并且从逻 ...
- C# 接口笔记
/* 1. 实现多态的两种方式. * 使用虚方法实现多态. * 使用抽象方法实现多态. * ...
- 日志管理-Log4net
引言 log4net库是Apache log4j框架在Micorsoft.NET平台的实现,是一个帮组程序员将日志信息输出到各种目标(控制台.文件.数据库等)的工具.(百度百科) 实际项目中使用log ...
- mysql 实战 or、in与union all 的查询效率
OR.in和union all 查询效率到底哪个快. 网上很多的声音都是说union all 快于 or.in,因为or.in会导致全表扫描,他们给出了很多的实例. 但真的union all真的快于o ...
- centos7最小安装后常常需要添加的命令
本人下载的最小镜像文件下载地址:http://pan.baidu.com/s/1kUD2jbT 原文地址:http://blog.csdn.net/nmgrd/article/details/5176 ...
- Linux crontab执行bash脚本
需要设置环境,bash文件的开头可以这么写 #!/bin/bash . /etc/profile . ~/.bash_profile
- GPS部标平台的架构设计(五)-地图服务算法库
GPS平台,需要和各种地图打交道,需要解决以下的问题: 1.坐标偏移,这个不用多说,需要将原始坐标加偏,然后在百度地图或谷歌上显示出来,需要注意的是百度地图的加偏是偏上再偏,谷歌.高德地图等是火星坐标 ...