服务器端
package Net.TCP;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket=new ServerSocket(8888);
Socket client=serverSocket.accept();
System.out.println("一个客户端建立了连接");
DataInputStream dis = new DataInputStream(client.getInputStream());
String data=dis.readUTF();
System.out.println(data);
dis.close();
}
}
客户端
package Net.TCP;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost", 8888);
DataOutputStream dos=new DataOutputStream(client.getOutputStream()) ;
String data="this is a test";
dos.writeUTF(data);
dos.flush();
dos.close();
client.close();
}
}