嗨,我正在尝试在python代码(作为PC上的服务器)和android应用(作为客户端-使用android Studios构建)之间实现TCP套接字
import socket
import sys
HOST = '192.168.1.10'
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('socket created')
#Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print ('Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1])
sys.exit()
print ('Socket Bind Success!')
#listen(): This method sets up and start TCP listener.
s.listen(10)
print ('Socket is now listening')
while 1:
conn, addr = s.accept()
print ('Connect with ' + addr[0] + ':' + str(addr[1]))
buf = conn.recv(64)
print (buf)
s.close()
和android主要活动为
package com.example.aneshkagoyal.socket;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
EditText t1;
// String str;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = findViewById(R.id.msg);
//str = t1.getText().toString();
b1 = findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Longrunning().execute(t1.getText().toString());
}
});
}
private class Longrunning extends AsyncTask<String,Void,Void>{
Socket s;
PrintWriter pw;
@Override
protected Void doInBackground(String... voids) {
try {
s = new Socket("192.168.1.10", 8888);
pw = new PrintWriter(s.getOutputStream());
pw.write(voids[0]);
pw.flush();
pw.close();
s.close();
}
catch (IOException e){
Log.e("error","error");
e.printStackTrace();
}
return null;
}
}
}
我已经在android上授予了用户互联网许可,但是我无法在他们之间建立通信…..由于我是新来的,所以请提供帮助