Android
public static void GetByHttpURL(final String url) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String resultData="";
URL connUrl=new URL(url);
HttpURLConnection urlConn= (HttpURLConnection)connUrl.openConnection ();
InputStreamReader in=new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer=new BufferedReader(in);
String inputLine=null;
while (((inputLine=buffer.readLine()) !=null)) {
resultData+=inputLine+"\n";
}
in.close();
urlConn.disconnect();
Log.d(TAG, "GetByHttpURL "+resultData);
} catch (Exception e) {
Log.d(TAG, "GetByHttpURL error "+e.getMessage());
e.printStackTrace();
}
}
}).start();
}
public static void GetByOkHttp(String url) {
try {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "GetByOkHttp onResponse: " + response.body().string());
}
});
} catch (Exception e) {
Log.d(TAG, "GetByOkHttp error "+e.getMessage());
e.printStackTrace();
}
}
public static void DoTcp() throws IOException, InterruptedException {
System.out.println("xiaosheng tcp:");
Log.d(TAG, "DoTcp bind tcp");
Socket socket = new Socket("192.168.3.5", 5000);
socket.setSoTimeout(10000);
//发送数据给服务端
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello,server".getBytes("UTF-8"));
Thread.sleep(2000);
socket.shutdownOutput();
//读取数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
//打印读取到的数据
Log.d(TAG, "tcp server recv:" + line);
br.close();
socket.close();
}
然后在Oncreate
里面添加如下代码,创建线程,激发一下
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Log.d(TAG, "start send http");
GetByOkHttp("http://missking.cc/");
GetByHttpURL("http://10.ip138.com");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
while(true){
DoTcp();
Thread.sleep(3000);
}
} catch (InterruptedException e) {
Log.d(TAG, "DoTcp error: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "DoTcp error: " + e.getMessage());
e.printStackTrace();
}
}
}).start();
}
python tcp server demo
server
def server():
'''
Server服务端程序
'''
# 如果放在服务器的话,填写云主机的内网IP 不是公网IP
server_ip = '0.0.0.0' # 绑定内网IP
server_port = 5000 # 监听端口
# 1.先调用socket.socket()创建socket套接字
# socket.AF_INET 表示ipv4
# SOCK_STREAM 表示使用tcp链接
# 2.bind()绑定监听的IP和端口
# 3.listen()开始监听
# 4.accept()接受客户端发来的消息
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((server_ip, server_port))
s.listen()
print("ready to connect:")
while True:
conn, client_ip = s.accept()
with conn:
print('Connected by', client_ip)
while True:
client_data = conn.recv(1024)
print("client:", client_data.decode())
if not client_data:
print('client data is null')
break
response_data = "hello client"+str(time.time())
response_data_byte = bytes(
response_data, encoding='utf-8')
conn.send(response_data_byte)
server()
client
# client1
import socket
import time
def send_data(data):
server_ip = '127.0.0.1' #服务器的IP
server_port = 5000 #服务器监听的端口
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((server_ip, server_port))
s.send(data)
data = s.recv(1024)
print('Received:', data.decode())
except Exception as e:
print('connect server fail(server ip %s,port %s):' % (server_ip, server_port))
print(e)
time.sleep(10)
continue
# return
send_data(bytes("hello server".encode("utf-8")))
client2
# client2
from socket import *
def tcpClient():
HOST = 'localhost' # or 'localhost'
PORT = 5000
BUFSIZ = 1024
ADDR=(HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
try:
tcpCliSock.connect(ADDR)
except Exception as e:
print("err:--",e)
while True:
data = "hello server"+str(time.time())
#print('data=',data);
if not data:
break
tcpCliSock.send(data.encode())
data = tcpCliSock.recv(BUFSIZ).decode()
if not data:
break
print("server:",data)
time.sleep(1)
tcpCliSock.close()
tcpClient()
补充
1.加权限
在AndroidManifest.xml里要加入网络权限
<uses-permission android:name="android.permission.INTERNET" />
2.导包
implementation("com.squareup.okhttp3:okhttp:4.9.1")
关于报错
这一句,一看是Client端报错
这个问题呢一般出现在数据的解码,或者encode
上
这个问题很容易让我们误会,让我们以为这是这一句错误,其实不是
s.connect((server_ip, server_port))
# 解决方法
send_data(bytes("hello server".encode("utf-8")))