模拟socket通信,创建两个java类
- ServerDemo
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by zhangyinyuan on 2016/12/22.
*/
public class ServerDemo {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(121);
while (true) {
System.out.println("开始阻塞等待请求");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
InetAddress inetAddress = socket.getInetAddress();
byte[] buf = new byte[1024];
int length = inputStream.read(buf);
String text = new String(buf, 0, length);
System.out.println("text:" + text + " inetAddress: " + inetAddress);
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- ClientDemo
package com.example;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("10.141.2.99", 121);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("tcp演示".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
// try {
// socket.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
}
至此,简单的通信已完成。
开始测试,注意:先运行ServerDemo,在运行ClientDemo。