客户端
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 8888);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeUTF( "我是客户端,请求连接");
System.out.print(dis.readUTF());
socket.close();
}catch (UnknownHostException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
服务端
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
System.out.print("服务器收到客户端的来链接请求"+ dis
.readUTF());
dos.writeUTF("接受连接请求成功!");
socket.close();
serverSocket.close();
}catch (
IOException e){
e.printStackTrace();
}
}
}
在终端执行命令
javac SocketServer.java
java SocketServer
javac SocketClient.java
java SocketClient
网友评论