java中的网络编程
利用socket编写一个简单的web服务器:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
protected void start(){
//声明一个套接字
ServerSocket s;
System.out.println("webserver start up on port 80");
System.out.println("press ctrl+c to exit");
try{
s = new ServerSocket(80);
}catch(Exception e){
System.out.println("Error:"+e);
return;
}
System.out.println("waiting for connection");
for(;;){
try{
//等待连接
Socket remote = s.accept();
System.out.println("connection ,sending data");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
PrintWriter out = new PrintWriter(remote.getOutputStream());
String str = ".";
while(!str.equals("")){
str = in.readLine();
System.out.println(str);
}
out.print("HTTP/1.0 200 OK");
out.print("Content-Type: text/html");
out.print("Server:Bot");
out.print("");
out.print("<H1>hellow 你好</H2>");
out.flush();
out.close();
remote.close();
}catch(Exception e){
System.out.println(e.toString());
}
}
}
public static void main(String[] args) {
WebServer ws = new WebServer();
ws.start();
}
}
一个客户端socket程序:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
public class Client {
public void go(){
try {
Socket s = new Socket("127.0.0.1",1234);
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message = reader.readLine();
System.out.println("获得来自服务器端的信息:"+message);
s.close();
reader.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client().go();
}
}
一个服务器端的socket程序:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Serverce {
public void go(){
try {
ServerSocket serversock = new ServerSocket(1234);
Socket sock = serversock.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
writer.write("hellow client");
writer.close();
sock.close();
serversock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Serverce().go();
}
}
python中的网络编程:
一个客户端socket程序:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect(('localhost',port))
print(s.recv(1024))
一个服务器端socket程序;
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind(('localhost',port))
s.listen(5)
while True:
c,addr= s.accept()
print('获得一个连接',addr)
c.send('你好客户端'.encode())
c.close()
需要注意的是,send和recv()接收的是字符串格式的字符,上面服务器端程序如果使用c.send('你好客户端')会产生一个错误
Traceback (most recent call last):
File "F:/PythonDemo/服务器程序.py", line 13, in <module>
c.send('你好客户端')
urllib
urlopen()函数可以像打开本地文件一样打开网络文件(urlopen函数在python3以后的版本中包含在urllib.request模块中)
urlretrieve()函数可以下载文件并在本地文件中储存一个文件的副本,函数返回一个元组(filename,header)filename是本地文件
名字,header包含一些远程文件信息,可以用第二个参数指定文件名
>>> urllib.request.urlretrieve('http://www.bilibili.com',r'f:\\bilibili.html')
('f:\\\\bilibili.html', <http.client.HTTPMessage object at 0x0159D330>)
socketserver:
一个基于socketserver的小型服务器
from socketserver import TCPServer,StreamRequestHandler
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print('获得连接',addr)
self.wfile.write('hellow client'.encode())
server = TCPServer(('',1234),Handler)
server.serve_forever()
一个使用了线程处理器的服务器:
from socketserver import TCPServer,StreamRequestHandler,ThreadingMixIn
class Server(ThreadingMixIn,TCPServer):pass
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print('获得连接',addr)
self.wfile.write('hellow client'.encode())
server = TCPServer(('',1234),Handler)
server.serve_forever()
python学习笔记6-socket
最新推荐文章于 2021-02-09 18:15:48 发布