OSI参考模型 TCP/IP参考模型
应用层
表示层 应用层
会话层
传输层 传输层
网络层 网络层
数据链路层 物理+数据链路层
物理层
IP协议 最大的贡献就是给大家提供了独一无二的IP地址。
A类地址 8位网络号并且0打头,24位主机号;
B类地址 16位网络号并且10打头,16位主机号;
C类地址 24位网络号并且110打头,8位主机号;
D类地址 1110打头,多播地址;
E类地址 1111打头,保留为今后使用。
Socket
/**
*Server端
**/
import java.net.*;
import java.io.*;
public class TestServer {
public static void main(String args[]) {
try {
ServerSocket s = new ServerSocket(8888);
while (true) {
Socket s1 = s.accept();
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello," + s1.getInetAddress() +
"port#" +s1.getPort() + " bye-bye!");
dos.close();
s1.close();
}
}catch (IOException e) {
e.printStackTrace();
System.out.println("程序运行出错:" + e);
}
}
}
import java.net.*;
import java.io.*;
public class TestClient {
public static void main(String args[]) {
try {
Socket s1 = new Socket("127.0.0.1", 8888);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
dis.close();
s1.close();
} catch (ConnectException connExc) {
connExc.printStackTrace();
System.err.println("服务器连接失败!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
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) );
//client自己占有9999端口
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}