Java TCP示例
Server端
- 初始化Socket
- 开始接受连接
- 得到InputStream
- 读取字节数组并转化为String
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket socket = null;
try {
socket = new ServerSocket(8080);
} catch (IOException e) {
e.printStackTrace();
}
try {
Socket client = socket.accept();
InputStream is = client.getInputStream();
byte[] buffer = is.readAllBytes();
String msg = new String(buffer);
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client端
- 初始化字节数组
- 初始化Socket
- 得到OutputStream
- 写入字节数组
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
byte[] buffer = "Hello World".getBytes();
try {
socket = new Socket("127.0.0.1", 8080);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}