05 April 2016

Ví dụ Servlet tính tổng

Servlet in java Enter number for loop  = sum



TCPServer.java

package network.sample;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

public static void main(String[] args) {
try {
ServerSocket myServer = new ServerSocket(9000);

Socket serverSocket = myServer.accept();

OutputStream os = serverSocket.getOutputStream();
InputStream is = serverSocket.getInputStream();

int a, n, tong = 0;
n = is.read();

for (int i = 0; i < n; i++) {
a = is.read();

tong += a;

}
System.out.println("Nhan: " + tong);
os.write(tong);
myServer.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

TCPClient.java

package network.sample;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);
System.out.println("Nhap vao n lan can tinh tong");
int n = s.nextInt();
try {
Socket myClient = new Socket("localhost", 9000);

OutputStream os = myClient.getOutputStream();
InputStream is = myClient.getInputStream();
os.write(n);
int num=0;
for (int i = 0; i < n; i++) {
System.out.print("Nhap so "+i+" : ");
os.write(s.nextInt());
}
int tong = is.read();
System.out.println("Tong: "+tong);
s.close();
myClient.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang