-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPClient.java
More file actions
37 lines (32 loc) · 1.29 KB
/
Copy pathTCPClient.java
File metadata and controls
37 lines (32 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class TCPClient {
public static void main(String[] args) throws Exception {
try{
// socket + connect
Socket socket = new Socket("127.0.0.1", 10000);
// Write + send to server
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
while (true) {
String input = sc.nextLine();
byte[] data = input.getBytes();
int header = data.length;
System.out.println("Send to server");
// message = [header, data]
bos.write(header);
bos.write(data);
bos.flush();
// Read
int dataLength = bis.read();
byte[] rcvData = new byte[dataLength];
bis.read(rcvData, 0, dataLength);
System.out.println("Receive from server:" + new String(rcvData));
}
} catch (Exception e) {
System.out.println("There is problem with server socket");
}
}
}