python java 用socket通信
程序员文章站
2022-03-02 08:11:53
...
python 客户端 代码
import socket
import sys
# ip为string, port 为int, msg为string
def socket_client(ip, port, msg):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
except socket.error as msg:
print("errer", msg)
sys.exit(1)
print("对方消息:" + s.recv(1024).decode('utf-8')) # 目的在于接受:Accept new connection from (...
s.send(msg.encode("utf-8"))
s.close()
if __name__ == '__main__':
ip = "127.0.0.1"
port = 9999
msg = "你好"
socket_client(ip, port, msg)
java 服务端
socketServer.java
import java.io.*;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try{
PrintWriter writer;
writer = new PrintWriter(socket.getOutputStream(), true);
while(true){
writer.println("你好,我是服务器");
break;
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
socket.getInputStream(), "utf-8"
)
);
String len = null;
while((len = reader.readLine()) != null){
System.out.println("client : " + len);
}
System.out.println("结束连接");
}catch(IOException e){
e.printStackTrace();
}
}
}
serverThread.java
package com.chat.juliciy_chat.utils;
import java.io.*;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try{
PrintWriter writer;
writer = new PrintWriter(socket.getOutputStream(), true);
while(true){
writer.println("你好,我是服务器");
break;
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
socket.getInputStream(), "utf-8"
)
);
String len = null;
while((len = reader.readLine()) != null){
System.out.println("client : " + len);
break;
}
System.out.println("结束连接");
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}