package TCP.LongConnection1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TCPServer {
private static ServerSocket serverSocket;
static {
try {
serverSocket = new ServerSocket(33321);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
while (true) {
try {
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
new Thread(() -> {
while (true) {
try {
System.out.println(dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
try {
dataOutputStream.writeUTF(scanner.next());
dataOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package TCP.LongConnection1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Scanner;
public class TCPClient {
private static Socket socket;
private static DataInputStream dataInputStream;
private static DataOutputStream dataOutputStream;
static {
try {
socket = new Socket("127.0.0.1", 33321);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Thread(() -> {
while (true) {
try {
System.out.println(dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
try {
dataOutputStream.writeUTF(scanner.next());
dataOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}