android studio 61歌曲服务器搭建 歌曲app 下载 完整代码
发布日期:2021-06-24 15:21:46 浏览次数:2 分类:技术文章

本文共 11046 字,大约阅读时间需要 36 分钟。

import socketimport sysfrom time import ctimedef 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 = 666# 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("E:\\KwDownload\\song\\", "http://xxxd39.vicp.cc/song/");            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()#netstat -aon|findstr 666#taskkill /f /t /im 4364
activity_main.xml
MainActivity.javapackage com.example.mymmusic;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;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; 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
arrayAdapter= new ArrayAdapter
( 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); 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]; 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+"%"); break; case 2: String[] strs=Path.split("/"); int lastSTR=0; for(int i=0,len=strs.length;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传递线程 */ Message message=new Message(); try {
outputStream=new FileOutputStream(file); byte [] buffer=new byte[1024*4]; FileLength=connection.getContentLength(); message.what=0; handler2.sendMessage(message); while (DownedFileLength
", DownedFileLength+""); Message message1=new Message(); message1.what=1; 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(); } }}androidManifest.xml
android:usesCleartextTraffic="true"

在这里插入图片描述

转载地址:https://blog.csdn.net/weixin_33595571/article/details/108090487 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android 62 自制域名解析 服务 花生壳太贵
下一篇:android studio 60音乐播放器 下载音乐

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月11日 10时22分04秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章