网络编程

Posted arroa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络编程相关的知识,希望对你有一定的参考价值。

通信协议:传输码率,代码结构,传输控制…..
TCP
面向连接,稳定
三次握手,四次挥手
UDP
面向无连接,不稳定
客户端、服务端:没有明确的界限

客户端
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
Socket socket = new Socket(serverIP,port);创建一个socket连接
OutputStream os = socket.getOutputStream();发送消息 IO流
服务器
建立服务的端口 ServerSocket
等待用户的链接 accept
接收用的消息

eg:文件上传
客户端
public class Demo1 {
public static void main(String[] args) throws IOException {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("C:\Users\张孛\Desktop\1许巍 - 曾经的你.mp3"));
Socket socket = new Socket("127.0.0.1",5555);
OutputStream outputStream = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
socket.shutdownOutput();
System.out.println("11111111111111");
InputStream inputStream1 = socket.getInputStream();
byte[] bytes1 = new byte[1024];
inputStream1.read(bytes1);
System.out.println(new String(bytes1));
socket.close();
}
}
服务器
public class Demo2 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
while (true){
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(System.currentTimeMillis()+""+new Random().nextInt(100)+".mp3"));
byte[] bytes = new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,len);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("已收到信息".getBytes());
socket.close();
}
}
}

UDP
不需要连接服务器

public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String msg = "发送给服务器";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 5555;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
socket.send(packet);
socket.close();
}
}


接收端

public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(5555);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}

以上是关于网络编程的主要内容,如果未能解决你的问题,请参考以下文章

Linux高级网络编程系列教程

Linux高级网络编程系列教程

面向对象编程面向组件编程面向方面编程面向服务编程

编程范式:命令式编程(Imperative)声明式编程(Declarative)和函数式编程(Functional)

少儿编程教育未来前景如何?我想加入少儿编程这行。

TCP/IP网络编程——理解网络编程和套接字编程