TCP协议学习简单案例
1.在TCP协议中,不用关闭流对象,关闭Socket和ServerSocket对象就可以了
2.传输中都是以字节输入输出流实现的
Client.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端
* Created by Aongi on 2017/5/4.
* Version 1.0
*/
public class Client {
//main方法
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8888);
//发送数据给服务器端
OutputStream os = socket.getOutputStream();
os.write("服务器你收到了吗?".getBytes());
//接受服务器端返回的数据
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int i = is.read(bytes);
System.out.println(new String(bytes,0,i));
//关闭socket对象
socket.close();
}
}
Server.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Aongi on 2017/5/4.
* Version 1.0
*/
public class Server {
//main方法
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
//接收客户端发送的消息
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int i = is.read(bytes);
System.out.println(new String(bytes,0,i));
//返回消息给客户端
OutputStream os = socket.getOutputStream();
os.write("我收到了!".getBytes());
//关闭socket对象,关闭serverSocket对象
socket.close();
serverSocket.close();
}
}