java socket 服务端 客户端

时间:2022-11-04 06:26:22

Server

package com.witwicky.socket.basicsocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; public class Server {
public static void main(String[] args) {
int port = 43523;
ServerSocket serverSocket = null;
try {
System.out.println("===\nstart recive message......"); serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); StringBuffer sb = new StringBuffer();
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1) {
System.out.println("length: " + len);
sb.append(new String(bytes, 0, len, "UTF-8"));
}
System.out.println(sb.toString());
System.out.println("end recive message......\n==="); String returnContent = "recive over.";
OutputStream outputStream = socket.getOutputStream(); outputStream.write(returnContent.getBytes("UTF-8")); outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Connected to the target VM, address: '127.0.0.1:61818', transport: 'socket'
===
start recive message......
length: 180
因为《The C Programme Language》中使用它做为第一个演示程序,非常著名,所以后来的程序员在学习编程或进行设备调试时延续了这一习惯。
end recive message......
===
Disconnected from the target VM, address: '127.0.0.1:61818', transport: 'socket' Process finished with exit code 0

Client

package com.witwicky.socket.basicsocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket; public class Client {
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 43523;
try {
System.out.println("===");
Socket socket = new Socket(host, port);
OutputStream outputStream = socket.getOutputStream(); String content = "因为《The C Programme Language》中使用它做为第一个演示程序,非常著名,所以后来的程序员在学习编程或进行设备调试时延续了这一习惯。";
outputStream.write(content.getBytes()); socket.shutdownOutput(); int len;
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
StringBuffer sb = new StringBuffer();
while ((len = inputStream.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len, "UTF-8"));
}
System.out.println("service return content: " + sb.toString());
System.out.println("==="); inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} }
}
Connected to the target VM, address: '127.0.0.1:61828', transport: 'socket'
===
service return content: recive over.
===
Disconnected from the target VM, address: '127.0.0.1:61828', transport: 'socket' Process finished with exit code 0