JAVA-TCP通信客户端服务端-基础

package Demo34;
/*
java.net.Socket 实现客户端套接字
Socket(String host,int port)
成员方法:
OutputStream getOutputStream() 返回套接字的输出流
InputStream getInputStream() 返回套接字的输入流
void close() 关闭次套接字
客户端和服务端交互,必须使用Socket中提供的网络流,不能使用自己创建的对象流
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Demo01TCPClient {
public static void main(String[] args) throws IOException {
//创建一个客户端对象Socket,构造方法中绑定服务器的IP,端口
Socket socket = new Socket(“127.0.0.1”,8888);
//使用socket对象的方法getOutputStream()获取网络字节输出流OutputStream对象
OutputStream os = socket.getOutputStream();
//使用网络字节输出流OutputStream对象中的方法write给服务器发送数据
os.write(“hello服务器”.getBytes());
//使用getInputStream()获取网络字节输入流
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println(new String(bytes,0,len)); //收到谢谢
socket.close();
}
}

package Demo34;
//java.net.ServerSocket
//构造方法:ServerSocket(int port)
//Socket accept() 侦听并接受次套接字的连接

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo02TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
Socket socket = server.accept();
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println(new String(bytes,0,len));//hello服务器
OutputStream os = socket.getOutputStream();
os.write(“收到谢谢”.getBytes());
socket.close();
server.close();
}
}

你可能感兴趣的:(JAVA的进阶之路,java)