客户端与服务器端时必须使用Socket中提供的网络流,不能使用自己创建的流对象。
客户端:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient {
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 in = socket.getInputStream();
byte[] b = new byte[1024];
int len = in.read(b);
System.out.println(new String(b, 0, len));
socket.close();
}
}
服务器端:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
Socket socket = server.accept();
OutputStream os = socket.getOutputStream();
os.write("收到,谢谢".getBytes());
InputStream in = socket.getInputStream();
byte[] b = new byte[1024];
int len = in.read(b);
System.out.println(new String(b, 0, len));
server.close();
socket.close();
}
}
先将服务器端运行,再去运行客户端,才能进行交互。
|