目录
1.用自己的IP和端口号创建一个Socket对象
Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9090);
2.获取一个输出流
OutputStream os = socket.getOutputStream();
3.进行数据写出
1.创建服务器端的ServerSocket,并指明自己的端口号
ServerSocket serverSocket=new ServerSocket(9090);
2.利用accept方法获取客户端的Scoket
Socket accept = serverSocket.accept();
3.获取一个输入流
InputStream inputStream = accept.getInputStream();
4.读入数据
功能:客户端将一份文件内容发送给服务端,服务端将文件保存在本地,并返回提示信息给客户端。
- package Network_programming;
-
- import org.junit.Test;
-
- import java.io.*;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
-
- public class demo5 {
- @Test
- public void server() throws IOException {
- //创建服务器端的ServerSocket,指明自己的端口号
- ServerSocket serverSocket=new ServerSocket(9090);
- //获取客户端的Scoket
- Socket accept = serverSocket.accept();
- //创建一个输入流
- InputStream inputStream = accept.getInputStream();
- FileOutputStream fos=new FileOutputStream("D:\\Java develop\\Program\\superior_Java\\ingram5.jpg");
- //写出数据
- int len;
- byte[]arr=new byte[20];
- while ((len= inputStream.read(arr))!=-1){
- fos.write(arr,0,len);
- }
- //反馈给客户端的信息
- OutputStream os=accept.getOutputStream();
- os.write("你好,服务端已经收到".getBytes());
- fos.close();
- inputStream.close();
- accept.close();
- serverSocket.close();
-
- }
- @Test
- public void client() throws IOException {
- //创建Socket对象
- Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9090);
- //获取一个输出流
- OutputStream os = socket.getOutputStream();
- FileInputStream fis=new FileInputStream(new File("D:\\Java develop\\Program\\superior_Java\\ingram.jpg"));
- //写出数据
- int len;
- byte []arr=new byte[20];
- while ((len= fis.read(arr))!=-1){
- os.write(arr,0,len);
- }
- //关闭数据的输出,不然服务器端会一直等待,造成阻塞
- socket.shutdownOutput();
- InputStream is=socket.getInputStream();
- ByteArrayOutputStream bis=new ByteArrayOutputStream();
- int length;
- byte []buffer=new byte[20];
- while ((length=is.read(buffer))!=-1){
- bis.write(buffer,0,length);
- }
- System.out.println(bis.toString());
-
- //接收服务器端的反馈信息
-
- //资源关闭
- os.close();
- fis.close();
- os.close();
- socket.close();
- }
-
- }
采用包进行传输,不必握手。类似于发短信。
- package Network_programming;
-
- import org.junit.Test;
-
- import java.io.IOException;
- import java.net.*;
-
- //UDP网络编程
- public class demo7 {
- @Test
- public void sender() throws IOException {
- DatagramSocket socket=new DatagramSocket();
- String str="你好,英格拉姆,希望你能带领鹈鹕夺冠啊!";
- byte []data=str.getBytes();
- DatagramPacket packet=new DatagramPacket(data,0,data.length, InetAddress.getLocalHost(),9090);
- socket.send(packet);
- socket.close();
- }
- @Test
- public void receiver() throws IOException {
- DatagramSocket socket=new DatagramSocket(9090);
- byte []arr=new byte[100];
- DatagramPacket packet=new DatagramPacket(arr,0,arr.length);
- socket.receive(packet);
- System.out.println(new String(packet.getData(),0, packet.getLength()));
- socket.close();
-
- }
-
- }