Java网络编程Socket通信

时间:2023-03-09 04:04:33
Java网络编程Socket通信

    TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议

    UDP (User Datagram Protocol 用户数据报协议)是OSI(Open System Interconnection开放式系统互联) 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务

TCP与UDP基本区别

  •   1.基于连接与无连接
  •   2.TCP要求系统资源较多,UDP较少; 
  •   3.UDP程序结构较简单 
  •   4.流模式(TCP)与数据报模式(UDP); 
  •   5.TCP保证数据正确性,UDP可能丢包 
  •   6.TCP保证数据顺序,UDP不保证 

一、Tcp协议通信

     1、Server服务器端:

  • a、创建ServerSocket对象,同时绑定监听端口
  • b、通过accept()方法监听客户端的请求
  • c、建立连接后,通过输入流读取客户端发送的请求信息
  • d、通过输出流向客户端发送响应信息
  • e、关闭相应资源
package com.yyx.test;

import java.io.File;
import java.io.FileInputStream;
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 TcpServerSocket {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
OutputStream outputStream = null;
FileOutputStream fileOutputStream = null;
try {
// 创建一个ServerSocket的对象,通过构造器指明自身的端口号
serverSocket = new ServerSocket(9090);
// 服务端监听 调用其accept()方法,返回一个Socket的对象
socket = serverSocket.accept();
inputStream = socket.getInputStream(); String pathname = "F:" + File.separator + "target.jpg";
File file = new File(pathname);
fileOutputStream = new FileOutputStream(file); /*
* 接收客户端发送文件,并保存到本地文件
*/
byte[] b = new byte[1024];
int len;
while ((len = inputStream.read(b)) != -1) {
fileOutputStream.write(b, 0, len);
} String strInfo = "你发送的图片我已接收成功!";
outputStream = socket.getOutputStream();
outputStream.write(strInfo.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭相应的流以及Socket、ServerSocket的对象
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }

 2、Client客户端:

  • a、创建Socket对象,指明需要连接的服务器的地址和端口号
  • b、建立连接后,通过输出流向服务器端发送请求信息
  • c、通过输入流获取服务器的响应信息
  • d、关闭相应资源
package com.yyx.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket; public class TcpClientSocket {
public static void main(String[] args) {
Socket socket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
FileInputStream fileInputStream=null;
try {
// 创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090); String pathname = "F:" + File.separator + "source.jpg";
File file = new File(pathname);
fileInputStream=new FileInputStream(file); // getOutputStream():发送数据,方法返回OutputStream的对象
outputStream = socket.getOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = fileInputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
} // shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
socket.shutdownOutput(); inputStream = socket.getInputStream();
byte[] bAnother = new byte[1024];
int lenAnother;
while ((lenAnother = inputStream.read(bAnother)) != -1) {
String str = new String(bAnother, 0, lenAnother);
System.out.print(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭相应的流和Socket对象,从后往前关闭
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

二、Udp协议通信

     客户端

package com.yyx.test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class UdpClientSocket {
public static void main(String[] args) {
DatagramSocket datagramSocket = null;
try {
datagramSocket = new DatagramSocket();
String str = "你好,我是要发送的数据";
byte[] b = str.getBytes(); /*
* 创建一个数据报:每一个数据报不能大于64k,都记录着数据信息,发送端的IP、端口号,以及要发送到 的接收端的IP、端口号
*/
DatagramPacket pack = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 9090); datagramSocket.send(pack);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (datagramSocket != null) {
datagramSocket.close(); }
}
}
}

服务端

package com.yyx.test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class UdpServerSocket {
public static void main(String[] args) {
DatagramSocket datagramSocket = null;
try {
datagramSocket = new DatagramSocket(9090);
byte[] b = new byte[1024];
DatagramPacket pack = new DatagramPacket(b, 0, b.length);
datagramSocket.receive(pack); String str = new String(pack.getData(), 0, pack.getLength());
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (datagramSocket != null) {
datagramSocket.close(); }
}
}
}