Cho em hỏi việc sử dụng cặp ngoặc () như bên dưới có ý nghĩa gì? Khi nào thì dùng nó?
Runnable runnable = () -> handleClientRequest(activeSocket);
handleClientRequest là hàm public static void nhận tham số là 1 đối tượng của lớp Socket.
Cho em hỏi việc sử dụng cặp ngoặc () như bên dưới có ý nghĩa gì? Khi nào thì dùng nó?
Runnable runnable = () -> handleClientRequest(activeSocket);
handleClientRequest là hàm public static void nhận tham số là 1 đối tượng của lớp Socket.
Trong java làm j có kiểu câu lệnh như trên?
Bác đang dùng IDE nào, Eclipse hay Intelji?
Chắc là Intelji 
@nguyenchiemminhvu thử click chuột vào đấy xem nó có expand cái code ra không.
Em học java ở java2s.com, nguyên code của nó đây ạ!
Phần Advance/Network
còn IDE thì em ít dùng Eclipse. Chỉ xem rồi code lại trên Sublime text 3 hoặc Notepad++ thôi. Biên dịch bằng javac vì đang học trên console. Em thử copy nguyên code đó vào notepad++ rồi biên dịch bằng javac vẫn ra đúng kết quả anh @ltd
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/* www .j a v a 2 s .co m*/
public class Main {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(12900, 100,
InetAddress.getByName("localhost"));
System.out.println("Server started at: " + serverSocket);
while (true) {
System.out.println("Waiting for a connection...");
final Socket activeSocket = serverSocket.accept();
System.out.println("Received a connection from " + activeSocket);
Runnable runnable = () -> handleClientRequest(activeSocket);
new Thread(runnable).start(); // start a new thread
}
}
public static void handleClientRequest(Socket socket) {
try{
BufferedReader socketReader = null;
BufferedWriter socketWriter = null;
socketReader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
socketWriter = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
String inMsg = null;
while ((inMsg = socketReader.readLine()) != null) {
System.out.println("Received from client: " + inMsg);
String outMsg = inMsg;
socketWriter.write(outMsg);
socketWriter.write("\n");
socketWriter.flush();
}
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
MÌnh cũng đoán là dùng Intelji, nó tự động collapse code :d, phím tắt là: ctrl + shift + Plus hoặc ctrl + shift + minus
Nó lỗi typing đó, bác thay đoạn đó bằng cái này:
Runnable runnable = new Runnable() {
@Override
public void run() {
handleClientRequest(activeSocket);
}
};
Runnable hình như là thread đấy ạ
chắc anh làm socket multithreading
nhưng mà kiểu khai báo thế kia thì ảo quá @@
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?