android studio 70 歌曲服务器搭建 歌曲app 完整代码(发布版)

111111 activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TabHost
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <!-- TabWidget组件id值不可变-->
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
            </TabWidget>
            <!-- FrameLayout布局,id值不可变-->
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_above="@android:id/tabs">
                <!-- 第一个tab的布局 -->
                <LinearLayout
                    android:id="@+id/tab1"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >
                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        xmlns:tools="http://schemas.android.com/tools"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="vertical">
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="0dp"
                            android:layout_weight="4"
                            android:orientation="horizontal">
                            <ListView
                                android:id="@+id/listView1"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_below="@+id/btn_test"
                                android:layout_marginTop="20dp" />
                        </LinearLayout>
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="0dp"
                            android:layout_weight="1"
                            android:gravity="bottom"
                            android:orientation="vertical">

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_weight="1"
                                android:orientation="horizontal">

                                <TextView
                                    android:id="@+id/music_current_time"
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    android:layout_weight="1"
                                    android:gravity="center"
                                    android:text="00:00"
                                    android:textStyle="bold"
                                    tools:autoText="false" />

                                <TextView
                                    android:id="@+id/textView"
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    android:layout_weight="4" />

                                <TextView
                                    android:id="@+id/music_total_time"
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    android:layout_weight="1"
                                    android:gravity="center"
                                    android:text="00:00"
                                    android:textStyle="bold" />
                            </LinearLayout>

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_weight="1"
                                android:orientation="horizontal">
                                <SeekBar
                                    android:id="@+id/music_seekbar"
                                    android:layout_width="0dp"
                                    android:layout_height="wrap_content"
                                    android:layout_weight="4" />
                            </LinearLayout>

                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_weight="1"
                                android:orientation="horizontal">

                                <ImageButton
                                    android:id="@+id/previous"
                                    android:layout_width="0dp"
                                    android:layout_height="match_parent"
                                    android:layout_weight="1"
                                    android:background="#00000000"
                                    android:src="@android:drawable/ic_media_previous" />

                                <ImageButton
                                    android:id="@+id/btn_pause"
                                    android:layout_width="0dp"
                                    android:layout_height="match_parent"
                                    android:layout_weight="1"
                                    android:background="#00000000"
                                    android:elevation="13dp"
                                    android:src="@android:drawable/ic_media_pause" />
                                <ImageButton
                                    android:id="@+id/next"
                                    android:layout_width="0dp"
                                    android:layout_height="match_parent"
                                    android:layout_weight="1"
                                    android:background="#00000000"
                                    android:src="@android:drawable/ic_media_next" />
                            </LinearLayout>
                        </LinearLayout>
                    </LinearLayout>

                </LinearLayout>

                <!-- 第二个tab的布局 -->
                <LinearLayout
                    android:id="@+id/tab2"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >
                    <EditText
                        android:id="@+id/editText"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="textPersonName"
                        android:text="请输入歌曲名称" />
                    <Button
                        android:id="@+id/button"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="搜索歌曲" />
                    <ProgressBar
                        android:id="@+id/progress"
                        style="?android:attr/progressBarStyleHorizontal"
                        android:layout_width="match_parent"
                        android:layout_height="25dp" />
                    <TextView
                        android:id="@+id/text"
                        android:layout_width="match_parent"
                        android:layout_height="20dp"
                        android:text="TextView" />
                    <ListView
                        android:id="@+id/ListName"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:text="Hello World!">
                    </ListView>
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>

222222 androidManifest.xml


	 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

	 android:usesCleartextTraffic="true"

33333 mainactivity.java

package com.example.download3;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TabHost;
import android.annotation.SuppressLint;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    TextView tv;
    ListView ls;
    Button btn;
    EditText edt;
    String NeedFindWords;
    String[] strArr;
    //    private static final String Path="http://192.168.1.2/song/2.DJ - 侧脸 (言寺).mp3";
    private ProgressBar progressBar;
    private TextView textView;
    private Button button;
    private int FileLength;
    private int DownedFileLength=0;
    private InputStream inputStream;
    private URLConnection connection;
    private OutputStream outputStream;

    //paly music need var..................
    private static final int INTERNAL_TIME = 1000;
    final MediaPlayer mp = new MediaPlayer();
    String song_path = "";
    private SeekBar seekBar;
    private TextView currentTV;
    private TextView totalTV;
    boolean isStop = true;
    private boolean isSeekBarChanging;//互斥变量,防止进度条与定时器冲突。
    private int currentposition;//当前音乐播放的进度
    private Timer timer;
    private ArrayList<String> list;
    private File[] songFiles;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            // 展示给进度条和当前时间
            int progress = mp.getCurrentPosition();
            seekBar.setProgress(progress);
            currentTV.setText(formatTime(progress));
            // 继续定时发送数据
            updateProgress();
            return true;
        }
    });

    //3、使用formatTime方法对时间格式化:
    private String formatTime(int length) {
        Date date = new Date(length);
        //时间格式化工具
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        String totalTime = sdf.format(date);
        return totalTime;
    }

    //download music need var.........
    private final int HANDLER_MSG_TELL_RECV = 0x124;
    @SuppressLint("HandlerLeak")
    Handler handlerDown = new Handler(){
        public void handleMessage(Message msg){
            //接受到服务器信息时执行
//            Toast.makeText(MainActivity.this,(msg.obj).toString(),Toast.LENGTH_LONG).show();
//            tv.setText((msg.obj).toString());
            System.out.println((msg.obj).toString());
            strArr = (msg.obj).toString().split("\n");

            ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String> (
                    MainActivity.this, android.R.layout.simple_list_item_1,strArr);
            ls.setAdapter(arrayAdapter);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabHost tab = (TabHost) findViewById(android.R.id.tabhost);
        //初始化TabHost容器
        tab.setup();
        //在TabHost创建标签,然后设置:标题/图标/标签页布局
        tab.addTab(tab.newTabSpec("tab1").setIndicator("本地音乐" , null).setContent(R.id.tab1));
        tab.addTab(tab.newTabSpec("tab2").setIndicator("网络音乐" , null).setContent(R.id.tab2));

        Button btn = findViewById(R.id.button);
        edt=(EditText)findViewById(R.id.editText);
        ls= (ListView) findViewById(R.id.ListName);
        //这个是文件下载控件
        progressBar=(ProgressBar) findViewById(R.id.progress);
        textView=(TextView) findViewById(R.id.text);
//        button=(Button) findViewById(R.id.button);

        //play music function
        totalTV = findViewById(R.id.music_total_time);
        currentTV = findViewById(R.id.music_current_time);
        seekBar = (SeekBar) findViewById(R.id.music_seekbar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());

        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
            return;
        }

        //判断是否是AndroidN以及更高的版本 N=24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        list = new ArrayList<String>();   //音乐列表   /sdcard/DownFile
        File sdpath = Environment.getExternalStorageDirectory(); //获得手机SD卡路径/sdcard/kgmusic/download
        System.out.println("******"+Environment.getExternalStorageDirectory());
        File path = new File(sdpath + "//DownFile");      //获得SD卡的mp3文件夹
        //返回以.mp3结尾的文件 (自定义文件过滤)
        songFiles = path.listFiles(new MyFilter(".mp3"));
        for (File file : songFiles) {
            list.add(file.getAbsolutePath());   //获取文件的绝对路径
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_single_choice,
                list);
        ListView li = (ListView) findViewById(R.id.listView1);
        li.setAdapter(adapter);
        li.setChoiceMode(ListView.CHOICE_MODE_SINGLE);


        li.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                song_path = ((TextView) view).getText().toString();
                currentposition = position;
                changeMusic(currentposition);
                try {
                    mp.reset();    //重置
                    mp.setDataSource(song_path);
                    mp.prepare();     //准备
                    mp.start(); //播放
                    seekBar.setMax(mp.getDuration());
                    isStop = false;
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (!isSeekBarChanging) {
                                seekBar.setProgress(mp.getCurrentPosition());
                            }
                        }
                    }, 0, 50);
                } catch (Exception e) {
                }
            }
        });

        //暂停和播放
        final ImageButton btnpause = (ImageButton) findViewById(R.id.btn_pause);
        btnpause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (song_path.isEmpty())
                    Toast.makeText(getApplicationContext(), "先选收歌曲先听听", Toast.LENGTH_SHORT).show();
                if (mp.isPlaying()) {
                    mp.pause();  //暂停
                    isStop = true;
                    btnpause.setImageResource(android.R.drawable.ic_media_play);
                } else if (!song_path.isEmpty()) {
                    mp.start();   //继续播放
                    isStop = false;
                    btnpause.setImageResource(android.R.drawable.ic_media_pause);
                }
            }
        });
        //上一曲和下一曲
        final ImageButton previous = (ImageButton) findViewById(R.id.previous);
        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeMusic(--currentposition);
            }
        });
        final ImageButton next = (ImageButton) findViewById(R.id.next);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeMusic(++currentposition);
            }
        });

        ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            private String MusicPath="";
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println(id);
                System.out.println("********************************************");
//                Toast.makeText(MainActivity.this,"点击了:"+position+"行",Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this,strArr[position],Toast.LENGTH_SHORT).show();
                MusicPath=strArr[position];
                //开启下载线程
                DownedFileLength=0;
                // TODO Auto-generated method stub
                Thread thread=new Thread(){
                    public void run(){
                        try {
                            DownFile(MusicPath);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                };
                thread.start();
//                System.out.println(strArr[position]);
//                System.out.println("********************************************");
            }
        });

//        tv= (TextView) findViewById(R.id.ReData);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 响应事件
                NeedFindWords=edt.getText().toString();
                startNetThread();
            }
        });
    }
    private void startNetThread() {
        new Thread() {
            @Override
            public void run() {
                try {
                    // 域名转化成IP  建立连接
                    String socketAddress ="xxxd39.vicp.cc";
                    InetAddress netAddress = InetAddress.getByName(socketAddress);
                    System.out.println("+++++++++"+netAddress.getHostAddress());
//                    Socket socket = new Socket(netAddress,8888);

                    Socket socket = new Socket(netAddress, 10020);
                    InputStream is = socket.getInputStream();
                    OutputStream out = socket.getOutputStream();
                    out.write(NeedFindWords.getBytes());					//3.发送
                    out.flush();
                    byte[] bytes = new byte[1024*4];
                    int n = is.read(bytes);
                    Message msg = handlerDown.obtainMessage(HANDLER_MSG_TELL_RECV, new String(bytes, 0, n));
                    msg.sendToTarget();
                    is.close();
                    socket.close();
                } catch (Exception e) {
                }
            }
        }.start();
    }

    private Handler handler2=new Handler()
    {
        public void handleMessage(Message msg)
        {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        progressBar.setMax(FileLength);
                        Log.i("文件长度----------->", progressBar.getMax()+"");
                        break;
                    case 1:
                        progressBar.setProgress(DownedFileLength);
                        int x=DownedFileLength*100/FileLength;
                        textView.setText("文件已下载:"+x+"%");
                        Log.i("音乐已经下载---------->", x+"");
                        break;
                    case 2:
//                        String[]  strs=Path.split("/");
//                        int lastSTR=0;
//                        for(int i=0,len=strs.length;i<len;i++){
//                            lastSTR=len;
//                            System.out.println(strs[i].toString());
//                        }
                        Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
//                        Toast.makeText(getApplicationContext(), strs[lastSTR-1].toString(), Toast.LENGTH_LONG).show();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    private void DownFile(String urlString)
    {
        String LastName="";
        /*
         * 连接到服务器
         */
        try {
            URL url=new URL(urlString);
            String[] MFileName=urlString.split("/");
            LastName=MFileName[MFileName.length-1];
            System.out.println("***********************"+LastName);
            connection=url.openConnection();
            if (connection.getReadTimeout()==5) {
                Log.i("---------->", "当前网络有问题");
                // return;
            }
            inputStream=connection.getInputStream();

        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*
         * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建
         */
        String savePAth= Environment.getExternalStorageDirectory()+"/DownFile";
        File file1=new File(savePAth);
        if (!file1.exists()) {
            file1.mkdir();
        }
        String savePathString=Environment.getExternalStorageDirectory()+"/DownFile/"+LastName;
        File file =new File(savePathString);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /*
         * 向SD卡中写入文件,用Handle传递线程 handler
         */
        Message message=new Message();
        try {
            outputStream=new FileOutputStream(file);
           // byte [] buffer=new byte[1024*4];有关系  大小有关
            byte [] buffer=new byte[1024*4];
            FileLength=connection.getContentLength();
            message.what=0;
            handler2.sendMessage(message);
//            while (DownedFileLength<FileLength) {
//                outputStream.write(buffer);// 文件大小有关
//                //outputStream.write(buffer,0,DownedFileLength);
//                DownedFileLength+=inputStream.read(buffer);
//                Log.i("-------->", DownedFileLength+"");
//                Message message1=new Message();
//                message1.what=1;
//                handler2.sendMessage(message1);
//            }
            int len = -1;
            while (DownedFileLength<FileLength&& (len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer,0,len);// 文件大小有关
                //outputStream.write(buffer,0,DownedFileLength);
                DownedFileLength+=len;
                Log.i("-------->", len+"");
                Message message1=new Message();
                message1.what=0x1;
                handler2.sendMessage(message1);
            }
            Message message2=new Message();
            message2.what=2;
            handler2.sendMessage(message2);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void changeMusic(int position) {
        if (position < 0) {
            currentposition = position = list.size() - 1;
        } else if (position > list.size() - 1) {
            currentposition = position = 0;
        }
        song_path = songFiles[position].getAbsolutePath();

        try {
            // 切歌之前先重置,释放掉之前的资源
            mp.reset();
            // 设置播放源
            mp.setDataSource(song_path);
            // 开始播放前的准备工作,加载多媒体资源,获取相关信息
            mp.prepare();
            // 开始播放
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        seekBar.setProgress(0);//将进度条初始化
        seekBar.setMax(mp.getDuration());//设置进度条最大值为歌曲总时间
        totalTV.setText(formatTime(mp.getDuration()));//显示歌曲总时长
        updateProgress();//更新进度条
    }

    private void updateProgress() {
        // 使用Handler每间隔1s发送一次空消息,通知进度条更新
        Message msg = Message.obtain();// 获取一个现成的消息
        // 使用MediaPlayer获取当前播放时间除以总时间的进度
        int progress = mp.getCurrentPosition();
        msg.arg1 = progress;
        mHandler.sendMessageDelayed(msg, INTERNAL_TIME);
    }

    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后,重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mp.seekTo(seekBar.getProgress());
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        if (mp != null) {
            mp.stop();
            mp.release();
        }
        Toast.makeText(getApplicationContext(), "退出啦", Toast.LENGTH_SHORT).show();
    }

}

444 MyFilter.java


import java.io.File;
import java.io.FilenameFilter;

class MyFilter implements FilenameFilter {
    private String type;

    public MyFilter(String type) {
        this.type = type;
    }

    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(type);
    }
}

python 服务器程序

import socket
import sys
from time import ctime

def FindMusicName(MusicName):
    f = open('musicName3.txt','r',encoding='utf8')
    for lines in f.readlines():
        if lines.find("马桃")!=-1:
            print(lines)
            print("find it .........................")
            return lines

# 1.socket(socket_family, socket_type, protocol=0)
# 其中,socket_family 是 AF_UNIX 或 AF_INET,ocket_type 是 SOCK_STREAM或 SOCK_DGRAM, protocol 通常省略,默认为 0。
# 为了创建 TCP/IP 套接字,可以用下面的方式调用 socket.socket()。
# tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 同样,为了创建 UDP/IP 套接字,需要执行以下语句。
# udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取本地机器名
host = socket.gethostname()

# 设置端口
port = 10020

# 2.s.bind绑定本地地址到socket对象
ServerSocket.bind((host, port))
# 3.s.listen监听地址端口,连接几个客户端
ServerSocket.listen(2)
while True:
    # 4.s.accept阻塞接受链接请求,被动接受 TCP 客户端连接,一直等待直到连接到达(阻塞)
    # accept()方法会返回一个含有两个元素的元组(fd,addr)。
    # 第一个元素是新的socket对象,服务器通过它与客户端通信。
    # 第二个元素也是元组,是客户端的地址及端口信息。
    clientsocket, addr = ServerSocket.accept()
    print("连接地址:%s" % str(addr))
    msg = "welcomt to my demo"
    all_line=""
    #send()和recv()的数据格式都是bytes。
    # (str和bytes的相互转化,用encode()和decode(),或者用bytes()和str())
    print("send msg:welcomt to my demo.")
    #clientsocket.send(msg.encode("utf-8"))
    data = clientsocket.recv(1024)
    print(data.decode("utf-8"))
    print("显示文件歌曲查询结果")
    f = open('musicName3.txt','r',encoding='utf8')
    for lines in f.readlines():
        if lines.find(data.decode("utf-8"))!=-1:
            print(lines)
            ReLines=lines.replace("F:\\KuGou\\", "http://xxxd39.vicp.cc/KuGou/");
            print("find it .........................")
            all_line=all_line+ReLines;
            continue
    data2= all_line.encode("utf-8")
    print(all_line)
    #data1 = ('[%s] %s' % (ctime(),data.decode())).encode("utf-8")
    clientsocket.send(data2)
    #clientsocket.send(str(MusicN).decode("utf-8"))
    clientsocket.close()
ServerSocket.close()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值