package Internet;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
// 服务端 :先有服务端再有客户端
public class Test16_Server {
public static void main(String[] args) throws IOException {
// 1. 得有一个地址(ServerSocket:服务端)
ServerSocket serverSocket=new ServerSocket(9999);
// 2.等待客户端连接
Socket socket=serverSocket.accept(); // 两个插座的端口号一样,所以两个插座是一样的
// 3. 读取客户端消息
InputStream is = socket.getInputStream();
// 4. 输出客户端信息
byte[] buffer = new byte[1024];
int length;
while ( ( length= is.read(buffer) ) != -1){
String msg=new String(buffer,0,length);
System.out.println(msg);
}
}
}
//////////////
package Internet;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
// 客户端
public class Test16_Client {
public static void main(String[] args) throws IOException {
// 1. 知道服务器(服务端)的IP和端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 2. 创建socket(插座)连接
Socket socket=new Socket(serverIP,port);
// 3. 发送消息,IO流
OutputStream os=socket.getOutputStream();
os.write("学习网络编程".getBytes());
// 4.关闭
os.close();
socket.close();
}
}
标签:java,socket,TCP,ServerSocket,import,Socket,客户端
From: https://www.cnblogs.com/zhanjianhai/p/17689316.html