-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp2ser.java
More file actions
99 lines (75 loc) · 3.86 KB
/
Copy pathtcp2ser.java
File metadata and controls
99 lines (75 loc) · 3.86 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.io.*;
import java.util.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public class tcp2ser {
public tcp2ser (){
}
public static void main (String [] args){ //java tcp2ser port_number
Socket socketClient = null;
ServerSocket socketServer = null;
if(args.length!=1){
System.out.println("You have to enter the parameters with this format: tcp2ser port_number");
} else {
String port = args[0]; //args[0] is the port_number
int portServer = Integer.parseInt(port);
try{
//to connect to the server
socketServer = new ServerSocket(portServer);
} catch (SocketException exception1) {
System.out.println("[ERROR] Socket: " + exception1.getMessage());
} catch (IOException exception2) {
System.out.println("[ERROR] IO: " + exception2.getMessage());
}
while(true){
try {
//to listen
socketClient = socketServer.accept();
ClientConnection newClient = new ClientConnection(socketClient);
Thread t1;
t1= new Thread(newClient);
t1.start();
System.out.println("There is a new client connected");
} catch (SocketException exception1) {
System.out.println("[ERROR] Socket: " + exception1.getMessage());
} catch (IOException exception2) {
System.out.println("[ERROR] IO: " + exception2.getMessage());
} //end second try
}//end while
} //end else
} //end main
static class ClientConnection implements Runnable {
int accumulator=0;
Socket socketClientConnection;
ClientConnection(Socket socketRreceived) {
socketClientConnection = socketRreceived;
}
public void run(){
try{
//we receive the information from the client
while(socketClientConnection.isConnected()){
DataInputStream infoClientToReceive = new DataInputStream(socketClientConnection.getInputStream());
String ask = new String(infoClientToReceive.readUTF());
String askBySpace[] = ask.trim().split(" ");
for (int i=0; i<askBySpace.length; i++) {
int number = Integer.parseInt(askBySpace[i]);
accumulator += number;
System.out.println("The accumulator is: " + accumulator);
}
//send the accumulator to the client
DataOutputStream infoServerToSend = new DataOutputStream(socketClientConnection.getOutputStream());
infoServerToSend.writeInt(accumulator);
} // end second while
} catch(Exception e){
System.out.println("The client has been disconnected");
}
//we close the socket
try{
socketClientConnection.close();
} catch(IOException exception2) {
System.out.println("[ERROR] IO: " + exception2.getMessage());
}
}//end run
}//end new class
}//end class