Java TCP编程
客户端
public class TcpClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 6666);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
System.out.println("输入发送的消息:");
Scanner scanner = new Scanner(System.in);
String sendMsg = scanner.nextLine();
os.write(sendMsg.getBytes());
socket.shutdownOutput();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
String msg = new String(buffer, 0 ,len);
System.out.println(msg);
}
os.close();
is.close();
socket.close();
}
}
服务端
public class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("serverSocket is running...");
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
String msg = new String(buffer, 0 ,len);
System.out.println(msg);
}
socket.shutdownInput();
os.write("ok".getBytes());
os.close();
is.close();
socket.close();
serverSocket.close();
}
}
|