SocketServer.java
package com.meowrain.tcpserver;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP01Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080);
System.out.println("Server is running... waiting for client to connect");
Socket socket = server.accept();
System.out.println("Connet successfully");
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int readLen = 0;
while ((readLen = inputStream.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, readLen));
}
server.close();
}
}
SocketCilent.java
package com.meowrain.tcpserver;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class SocketTCP01Cilent {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 8080);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Hello, I am client".getBytes());
socket.close();
System.out.println("Connet over");
}
}