---------------------- <a href="http://edu.youkuaiyun.com"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.youkuaiyun.com"target="blank">.Net培训</a>、期待与您交流! ----------------------
1.tcp 有连接可靠 对传输大小没限制 像打电话 传输的是socket对象(封装了数据) socket serversocket 必须先启动服务端
2.udp 无连接 不可靠 对传输有限制64k(一个包)像发短信 传输的是包(真实数据)两个类 datagramsocket datagrampacket 发送端和接收端谁先开都行
最主要的区别 udp 是传输数据包发送和接收是直接操作数据 而tcp传输的是socket对象(封装了数据) 服务器端是操作socket对象间接操作对象 关闭的socket是客户端socket
udp代码
class Send implements Runnable {
private DatagramSocket ds;
public Send(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
byte[] buf = new byte[1024*64];
DatagramPacket dp = null;
String line = null;
while((line = br.readLine())!=null){
if("88".equals(line))
break;
buf = line.getBytes();
dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"),10001);
ds.send(dp);
}
} catch (Exception e) {
throw new RuntimeException("发送出现错误");
}
}
}
class Receive implements Runnable {
private DatagramSocket ds;
public Receive(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
while(true){
byte[] buf = new byte[1024*64];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
System.out.println(new String(dp.getData()));
}
} catch (Exception e) {
throw new RuntimeException("接收出现错误");
}
}
}
public class UDPChar {
public static void main(String[] args) throws Exception {
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receiveSocket = new DatagramSocket(10001);
new Thread(new Send(sendSocket)).start();
new Thread(new Receive(receiveSocket)).start();
}
}
1.发送端和接收端都有 packet与socket
2.发送的和接收端的socket都应该有一个端口号 接收端必须有 发送端如果没有系统指定
3.packet 发送端和接收端不同 发送的应该指明发送地址与端口号 接收端只需接收就行
TCP代码
客户端
public class TCPClient {
public static void main(String[] args) throws UnknownHostException, Exception {
Socket socket = new Socket("127.0.0.1",20000);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
os.write("niaho".getBytes());
byte[] arr = new byte[8192];
int lengh = is.read(arr);
System.out.println(new String(arr));
socket.close();
}
}
服务器端
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(20000, 10);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
os.write("niaho".getBytes());
byte[] arr = new byte[8192];
int lengh = is.read(arr);
System.out.println(new String(arr));
ss.close(); //关闭客户端
}
}
1.客户端 是socket 服务器端是serversocket 但操作的都是客户端传过来的socket对象
2.客户端要指明发送端口和目的ip 服务器端只需指明端口就行
3.操作用的都是io 把数据放到对象中传到服务器端 服务器操作 客户端的socket
---------------------- <a href="http://edu.youkuaiyun.com"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.youkuaiyun.com"target="blank">.Net培训</a>、期待与您交流! ----------------------