目录
TCP
消息传输
文件传输
UDP
消息发送
聊天实现
URL
TCP
消息传输
客户端:
package com.company;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket =null;
OutputStream os =null;
try {
//要知道服务器的地址,端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//创建一个socket链接
socket = new Socket(serverIP,port);
//发送消息IO流
os = socket.getOutputStream();
os.write("你好".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器端:
package com.company;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket=null;
InputStream is =null;
ByteArrayOutputStream baos=null;
try {
//我得有一个地址
serverSocket =new ServerSocket(9999);
//等待连接
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 {
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();
}
}
}
}
文件传输
客户端:
package com.company;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket =null;
OutputStream os =null;
InputStream is =null;
FileInputStream fis =null;
ByteArrayOutputStream baos =null;
try {
//创建一个Socket链接
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(serverIP,port);
//创建一个输出流
os = socket.getOutputStream();
//读取文件
fis=new FileInputStream(new File("src/桌面.jpg"));
//写出文件
byte[] buffer = new byte[1024];
int len;
while((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
//发送消息
os = socket.getOutputStream();
os.write("你好".getBytes());
//通知服务器我已经结束了
socket.shutdownOutput();//传输完成
//确定服务器接收完毕,才能断开连接
is= socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer2= new byte[1024];
int len2;
while((len2 = is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器端:
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket=null;
InputStream is =null;
ByteArrayOutputStream baos=null;
FileOutputStream fos =null;
OutputStream os= null;
try {
//创建服务
serverSocket =new ServerSocket(9999);
//监听等待客户端连接
socket = serverSocket.accept();//阻塞式监听,一直等待客户端链接
//获取输入流
is = socket.getInputStream();
//文件输出
fos = new FileOutputStream(new File("recive.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len =is.read(buffer))!=-1 ){
fos.write(buffer,0,len);
}
//通知客户端我接受完毕了
os = socket.getOutputStream();
os.write("我接受完毕了,你可以断开了".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fos.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();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
UDP
消息发送
package com.company.UDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//UDP不需要连接服务器
public class UDPclient {
public static void main(String[] args) throws IOException {
//建立一个Socket
DatagramSocket socket = new DatagramSocket();
//建立一个包
String msg = "hello";
InetAddress localhost =InetAddress.getByName("localhost");
int port = 9090;
//参数:数据,数据长度,起始,端口号
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
//发送包
socket.send(datagramPacket);
socket.close();
}
}
package com.company.UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//等待客户端链接
public class UDPserver {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket ds =new DatagramSocket(9090);
//接收数据包
byte[] buffer = new byte[1024];
DatagramPacket dp=new DatagramPacket(buffer,0,buffer.length);
ds.receive(dp);
System.out.println(new String(dp.getData(),0,dp.getLength()));
ds.close();
}
}
聊天实现
一共有四个类:
1.发送信息TalkSend类
package com.company.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class TalkSend implements Runnable{
DatagramSocket socket =null;
BufferedReader reader =null;
private int fromIP;
private String toIP;
private int toPort;
public TalkSend(int fromIP, String toIP, int toPort) {
this.fromIP = fromIP;
this.toIP = toIP;
this.toPort = toPort;
try{
socket = new DatagramSocket(fromIP);
reader = new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
//准备数据
while (true){
String data = null;
try {
data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
2.接收信息TalkReceive类
package com.company.chat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable {
DatagramSocket socket =null;
private int port;
private String msgf;
public TalkReceive(int port,String msgf) {
this.port = port;
this.msgf = msgf;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);
System.out.println();
//断开连接
byte[] data =packet.getData();
String rd = new String(data,0,data.length);
System.out.println(msgf+":"+rd);
if (rd.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.用户1类(学生)TalkStudent
package com.company.chat;
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(8888,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
4.用户2类(老师)TalkTeacher
package com.company.chat;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(9999,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}
URL
? ? ? ? 统一资源定位符:定位互联网上某一个资源
协议://IP地址:端口/项目名/资源
URL url = new URL("https://www.baidu.com");
//得到协议名
url.getProtocol();
//得到主机ip
url.getHost();
//端口号
url.getPort();
//文件地址
url.getPath();
//得到文件
url.getFile();
通过URL下载文件:
package com.company;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
URL url = new URL("http://127.0.0.1:8080/songyi/sy.txt");
//链接资源
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("sy.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
fileOutputStream.close();
is.close();
urlConnection.disconnect();//断开连接
}
}
|