Java | TCP/IP協議下的Socket報文通信

背景

客戶端將用戶寫入的音頻文件或音頻流傳送給服務端
服務端通過訊飛AI進行語音轉寫後將文本文件傳送回客戶端

建立socket通信的服務端和客戶端

實現客戶端服務端傳送音頻文件

/*
 * Server.java 
 */
import java.io.*;
import java.net.*;


public class Server 
{
    public static void main(String[] args) throws Exception 
    {
    	//final String client = "Client:";
        //final String server = "Server:";
    	int port = 4000;
    	String savePath="E:\\intern2019_test\\2";
    	ServerSocket serverSocket = new ServerSocket(port);  
    	Socket socket = serverSocket.accept();
    	DataInputStream dis=null;
    	dis = new DataInputStream(new BufferedInputStream(socket 
                 .getInputStream()));
    	int bufferSize = 1024;
    	byte[] buf = new byte[bufferSize]; 
        int passedlen = 0; 
        long len = 0; 
        savePath += dis.readUTF(); 
        DataOutputStream fileOut = new DataOutputStream( 
            new BufferedOutputStream(new BufferedOutputStream( 
                new FileOutputStream(savePath)))); 
        len = dis.readLong(); 
        System.out.println("文件的長度爲:" + len + "    KB"); 
        System.out.println("開始接收文件!");
        while (true) { 
            int read = 0; 
            if (dis!= null) { 
              read = dis.read(buf); 
            } 
            passedlen += read; 
            if (read == -1) { 
              break; 
            } 
            //System.out.println("文件接收了" + (passedlen * 100 / len) + "%"); 
            fileOut.write(buf, 0, read); 
          } 
        System.out.println("接收完成,文件存爲" + savePath); 
        fileOut.close();
    	socket.close();
        serverSocket.close();
    }
}
/*
 * Client.java
 */
import java.io.*;
import java.net.*;

public class Client
{
	public static void main(String []args) throws Exception{
        //final String client = "Client:";
        //final String server = "Server:";
        
        int port = 4000;
        byte ipAddressTemp[] = {127, 0, 0, 1};
        InetAddress ipAddress = InetAddress.getByAddress(ipAddressTemp);
        Socket socket = new Socket(ipAddress, port);
        String filepath="E:\\intern2019_test\\test.wav";
        DataOutputStream dos=null;
		DataInputStream dis=null;
		File file=new File(filepath);
		dos=new DataOutputStream(socket.getOutputStream());
		dis=new DataInputStream(new BufferedInputStream(new FileInputStream(filepath)));
		int buffferSize=1024;
		byte[]bufArray=new byte[buffferSize];
		dos.writeUTF(file.getName()); 
		dos.flush(); 
		dos.writeLong((long) file.length()); 
		dos.flush(); 
		while (true) { 
		    int read = 0; 
		    if (dis!= null) { 
		      read = dis.read(bufArray); 
		    } 

		    if (read == -1) { 
		      break; 
		    } 
		    dos.write(bufArray, 0, read); 
		  } 
		dos.flush();
		if (dos != null)
		{
	          dos.close();
		}
		if (dis != null) 
		{     
			dis.close(); 
		}
		if (socket != null)
		{	
			socket.close();
		}
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章