java socket
计算机网络知识不做赘述
一、InetAddress类
public static void main(String[] args) {
try {
System.out.println("--------获取ip地址-------");
InetAddress byName = InetAddress.getByName("192.168.43.8");
System.out.println(byName);
System.out.println("--------根据域名获取ip地址-------");
InetAddress n2 = InetAddress.getByName("www.baidu.com");
System.out.println(n2);
System.out.println(n2.getHostName()); //获取ip对应的域名
System.out.println(n2.getHostAddress()); //获取IP地址
System.out.println("--------获取本地址-------");
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
二、TCP编程
可靠,效率低
客户端:
-
创建Socket对象,指明服务器端的ip
-
获取一个输出流,用于输出数据
-
写出数据
-
关闭资源
public class client { private static String ip="127.0.0.1"; private static int port=8000; public static void main(String[] args) { /* * 1. 创建Socket对象,指明服务器端的ip 2. 获取一个输出流,用于输出数据 3. 写出数据 4. 关闭资源 * */ InetAddress ipAddr = null; Socket socket = null; OutputStream os = null; try { ipAddr = InetAddress.getByName(ip); socket = new Socket(ipAddr, port); os = socket.getOutputStream(); while(true){ os.write("你好~~".getBytes()); Thread.currentThread().sleep(3000); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
服务器端:
-
创建服务器端SeverSocket对象,指明端口
-
接收来自客户端的socket
-
获取输入流
-
读取数据
-
关闭资源
public class server { private static int port = 8000; public static void main(String[] args) { /* 1. 创建服务器端SeverSocket对象,指明端口 2. 接收来自客户端的socket 3. 获取输入流 4. 读取数据 5. 关闭资源 * */ ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; ByteOutputStream bos = null; try { serverSocket = new ServerSocket(port); socket = serverSocket.accept(); inputStream = socket.getInputStream(); bos = new ByteOutputStream(); int len = 0; byte [] buf = new byte[10]; while((len = inputStream.read(buf)) != -1){ bos.write(buf,0,len); System.out.println(bos.toString()); } } catch (IOException e) { e.printStackTrace(); } finally { if(bos != null){ bos.close(); } 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(); } } } } }
三、UDP编程
不可靠,效率高
客户端:
- 创建DatagramSocket对象
- 创建datagramPacket数据包对象
- 发送数据
- 关闭连接
public class client {
private static String ip = "127.0.0.1";
private static int port = 8000;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DatagramSocket datagramSocket = null;
DatagramPacket datagramPacket = null;
try{
datagramSocket = new DatagramSocket();
while(true){
String s = sc.next();
byte [] buf = s.getBytes();
if(!"q".equals(s) && !"Q".equals(s)){
datagramPacket = new DatagramPacket(buf,0,buf.length,InetAddress.getByName(ip),port);
datagramSocket.send(datagramPacket);
}else{
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(datagramSocket != null){
datagramSocket.close();
}
}
}
}
服务器端:
- 创建DatagramSocket对象
- 创建datagramPacket数据包对象
- 接收数据
- 关闭连接
public class sever {
private static int port = 8000;
public static void main(String[] args) {
DatagramSocket datagramSocket = null;
byte [] buf = new byte[100];
DatagramPacket datagramPacket = null;
try {
datagramSocket = new DatagramSocket(port);
datagramPacket = new DatagramPacket(buf, 0, buf.length);
while (true){
datagramSocket.receive(datagramPacket);
System.out.println(datagramPacket.getAddress() + ":" + new String(datagramPacket.getData(),0,datagramPacket.getLength()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
datagramSocket.close();
}
}
}
四、URL编程
URL类
public static void main(String[] args) {
try {
URL url = new URL("http://127.0.0.1:8080/MyWeb/hwllo.html?uername=zjj");
System.out.println(url.getProtocol()); //获取协议名称
System.out.println(url.getHost()); //获取IP地址
System.out.println(url.getPort()); //获取端口号
System.out.println(url.getPath()); //路径资源
System.out.println(url.getQuery()); //获取参数
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
URL访问服务器下载图片
public static void main(String[] args) {
HttpURLConnection conn = null;
InputStream inputStream = null;
FileOutputStream fos = null;
try {
URL url = new URL("http://localhost:8080/jsp/zxy.png");
conn = (HttpURLConnection) url.openConnection();
conn.connect();
inputStream = conn.getInputStream();
fos = new FileOutputStream("zxy.png");
byte[] buf = new byte[1024];
int len =0;
while((len = inputStream.read(buf)) != -1){
fos.write(buf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(conn != null){
conn.disconnect();
}
}
}
实例:
一、实现传输文件至本地(此处用图片)
实现:socket+io
客户端:
public static void main(String[] args) {
BufferedInputStream bis = null;
Socket socket = null;
OutputStream os = null;
InputStream is = null;
try {
bis = new BufferedInputStream(new FileInputStream("C:\\Users\\18255\\Desktop\\zxy.png"));
socket = new Socket(InetAddress.getByName("127.0.0.1"), 8000);
os = socket.getOutputStream();
is = socket.getInputStream();
int len = 0;
byte [] buf = new byte[1024];
while((len = bis.read(buf)) != -1){
os.write(buf,0,len);
}
socket.shutdownOutput(); //给服务器传传输完成指令
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte [] buf2 = new byte[20];
int len1 = 0;
while((len1 = is.read(buf2)) != -1){
bos.write(buf2,0,len1);
}
System.out.println(bos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
BufferedOutputStream bos = null;
OutputStream os = null;
try {
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
is = socket.getInputStream();
bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\18255\\Desktop\\socketFile.png"));
int len = 0;
byte [] buf = new byte[1024];
while((len = is.read(buf)) != -1){ //由于read是阻塞式的,所以需要在客户端给出停止传输指令才能跳出循环
bos.write(buf,0,len);
}
os = socket.getOutputStream();
os.write("complete~".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.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();
}
}
}
}
二、使用UDP实现双向通信
实现方式:开启双线程一个用于接收,另一个用于发送
客户端:
public class client {
public static void main(String[] args) {
Send send = new Send();
Recive recive = new Recive();
Thread t1 = new Thread(send);
t1.setName("发送线程");
Thread t2 = new Thread(recive);
t2.setName("接收线程");
t1.start();
t2.start();
}
}
/*发送*/
class Send implements Runnable{
@Override
public void run() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入对方的ip地址:");
String ip = sc.next();
InetAddress ipaddr = InetAddress.getByName(ip);
System.out.println("请输入对方的额端口号:");
int port = sc.nextInt();
DatagramSocket socket = null;
DatagramPacket datagramPacket = null;
try{
socket = new DatagramSocket();
byte []buf = null;
while(true){
//System.out.println("请输入信息:");
String s = sc.next();
buf = s.getBytes();
datagramPacket = new DatagramPacket(buf,0, buf.length,ipaddr,port);
socket.send(datagramPacket);
}
}catch(Exception e){
e.printStackTrace();
}finally {
socket.close();
}
}
}
/*接收*/
class Recive implements Runnable{
@Override
public void run() {
Scanner sc = new Scanner(System.in);
DatagramSocket socket = null;
DatagramPacket datagramPacket = null;
try {
socket = new DatagramSocket(8000);
byte []buf = new byte[100];
while(true){
datagramPacket = new DatagramPacket(buf, 0, buf.length);
socket.receive(datagramPacket);
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null){
socket.close();
}
}
}
}
服务端:
public class sever {
public static void main(String[] args) {
Send1 send = new Send1();
Recive1 recive = new Recive1();
Thread t1 = new Thread(send);
t1.setName("发送线程");
Thread t2 = new Thread(recive);
t2.setName("接收线程");
t1.start();
t2.start();
}
}
/*发送*/
class Send1 implements Runnable{
@Override
public void run() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入对方的ip地址:");
String ip = sc.next();
InetAddress ipaddr = InetAddress.getByName(ip);
System.out.println("请输入对方的额端口号:");
int port = sc.nextInt();
DatagramSocket socket = null;
DatagramPacket datagramPacket = null;
try{
socket = new DatagramSocket();
byte []buf = null;
while(true){
//System.out.println("请输入信息:");
String s = sc.next();
buf = s.getBytes();
datagramPacket = new DatagramPacket(buf,0, buf.length,ipaddr,port);
socket.send(datagramPacket);
}
}catch(Exception e){
e.printStackTrace();
}finally {
socket.close();
}
}
}
/*接收*/
class Recive1 implements Runnable{
@Override
public void run() {
Scanner sc = new Scanner(System.in);
DatagramSocket socket = null;
DatagramPacket datagramPacket = null;
try {
socket = new DatagramSocket(8001);
byte []buf = new byte[100];
while(true){
datagramPacket = new DatagramPacket(buf, 0, buf.length);
socket.receive(datagramPacket);
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null){
socket.close();
}
}
}
}
以上服务器于客户端基本一致,所以可以不区分服务器与客户端,谁先开启谁就是服务端(UDP才可以,TCP只能服务端先开启)