TCP(用户传输协议)
客户端
- 通过socket连接服务器
- 发送消息
public static void main(String[] args) throws Exception {
Socket socket = null;
OutputStream outputStream = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,9999);
outputStream = socket.getOutputStream();
outputStream.write("Hello World!".getBytes());
}catch (Exception e) {
e.printStackTrace();
}finally {
outputStream.close();
socket.close();
}
}
客户端:
- 建立服务器端口ServerSocket
- 等待用户的连接 accept
- 接受用户的消息
public static void main(String[] args) throws Exception {
Socket accept = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
ServerSocket serverSocket = new ServerSocket(9999);
while (true) {
accept = serverSocket.accept();
inputStream = accept.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while((len = inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes,0,len);
}
System.out.println(new String(byteArrayOutputStream.toString()));
}
}catch (Exception e) {
e.printStackTrace();
}finally {
byteArrayOutputStream.close();
inputStream.close();
accept.close();
}
}
注意:以上代码都进行try catch处理,我是为了减少代码量,部分没有处理
知是行之始,行是知之成
|