JAVA网络编程基础
要素
ip地址:ip号和端口号,下面代码用于获取当前ip地址
InetAddress ip4 = Inet4Address.getLocalHost();
System.out.println(ip4.getHostAddress());
通信协议:网络通信协议
网络通信主要使用TCP和UDP
类(包:java.net.InetAddress)
获得ip:InetAddress.getByName
本机 localhost
端口表示计算机上的一个程序的进程:
不同的进程有不同的端口号!用来区分软件
端口范围:0-65535
端口分类:
公有端口:0-1023**(HTTP:80,HTTPS:443,FTP:21,Telent:23)**
程序注册端口:1024-49151**(Tomcat:8080,MySQL:3306,Oracle:1521)**
动态,私有端口:49152-65535
通信协议
tcp/ip协议簇
tcp:用户传输协议
udp:用户数据报协议
使用tcp实现通信(单向,多线程还没学)
客户端代码(注意:关闭资源前要判空,下面代码只判了一个)
public class Client01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os =null;
try {
InetAddress ServerIP = InetAddress.getByName("172.16.6.49");
int port=9999;
socket = new Socket(ServerIP,port);
os = socket.getOutputStream();
os.write("实验成功,seeyou".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端代码
public class server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is= null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
while(true) {
socket = serverSocket.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
System.out.println(baos.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(baos!=null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件上传
客户端
public class Client02 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("192.168.100.54"), 9000);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("src/fengxing.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
fis.close();
os.close();
socket.close();
}
}
服务端
public class server02 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("receive.png"));
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
|