注:学习马士兵的视频,欢迎讨论。
1.简单了解网络传输分层结构和概念;了解TCP和UDP。
2.tcp和udp是两种网络通信方式,tcp是面向链接的通信方式,需要优先建立通信管道;
udp是无连接传输,因而需要将通信数据存储打包发送(先建一个存储容器/空间);tcp
可靠但低效率传输;udp高效但不可靠。udp通信,数据包传输要保证正确的打包,并正确
接收解包,才能保证通信的数据正确和完整。
3.计算机端口号是用于区分各个不同使用中应用程序的标识;32位计算机的端口可以有65536
个不同的tcp、udp端口;同一个应用程序可以占用多个端口。
4.两个java程序可以通过双向的网络链接实现数据通信,这双向链接的每一端就是一个Socket。
5.java。net中的SocketServer和Socket用于TCP数据通信的服务器和客服端;DatagramPacket和
DatagramSocket用于UDP的数据通信设计。Tcp中服务器使用accept()接受客服端的通信;Udp
使用receive()来接收通信数据。
6,SOCKET通信需要接受端的IP地址和服务端口号。
7,服务器运行中不断地accept()和receive(),等待客户端的数据请求;没有请求就一直挂住。
样例:
1.TCP数据通信
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
while(true) {
Socket s = ss.accept();
System.out.println("a client connect!");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
}
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 6666);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
Thread.sleep(3000);
dos.writeUTF("hello server!");
dos.flush();
dos.close();
s.close();
}
}
2.UDP数据通信
import java.net.*;
import java.io.*;
public class TestUDPServer
{
public static void main(String args[]) throws Exception
{
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while(true)
{
ds.receive(dp);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
DataInputStream dis = new DataInputStream(bais);
System.out.println(dis.readLong());
}
}
}
import java.net.*;
import java.io.*;
public class TestUDPClient
{
public static void main(String args[]) throws Exception
{
long n = 10000L;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(n);
byte[] buf = baos.toByteArray();
System.out.println(buf.length);
DatagramPacket dp = new DatagramPacket(buf, buf.length,
new InetSocketAddress("127.0.0.1", 5678)
);
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}