我有問題。 我不完全理解客戶端和服務器套接字是如何工作的? 我明白的是 當一個服務器套接字被創建時,它有很多可以打開的端口.socket對象是在連接到服務器套接字的不同端口的服務器端創建的。連接到服務器套接字的套接字連接到客戶端套接字並完成連接?瞭解客戶端和服務器插座
我是對還是錯?
public class TryThreads extends Thread
{
private int Portnumber;
private static String inputLine;
public TryThreads(int portNumber)
{
Portnumber = portNumber;
setDaemon(false);
}
public static void main(String[] args)
{
//create three threads
Thread first = new TryThreads(63400);
Thread second = new TryThreads(63401);
first.start();
second.start();
//third.start();
System.out.println("ending main");
return;
}
public void run()
{
//System.out.println("one socket port opened");
try
{
System.out.println("one socket port opened");
ServerSocket serverSocket = new ServerSocket(Portnumber);
System.out.println("one socket port opened");
while (true)
{
System.out.println("ending main2");
//System.out.println("one socket port opened");
Socket clientSocket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
while((inputLine = bufferedReader.readLine()) != null)
System.out.println(inputLine);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
和客戶端
public class client
{
private static PrintWriter printWriter;
public static void main(String[] args)
{
BufferedReader in = null;
try
{
Socket socket = new Socket("localhost",63400);
printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("Hello Socket");
printWriter.println("EYYYYYAAAAAAAA!!!!");
socket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
您可以簡單閱讀本文並查看您的代碼。 http://www.javaworld.com/article/2077322/core-java/sockets-programming-in-java-a-tutorial.html或者http://www.codeproject。com/Articles/24600 /使用-Java-Server中的套接字 學習某件事的最好方法是由你做到這一點,然後你會記得更多。 – RMachnik
http://www.docjar.com/html/api/java/net/Socket.java.html或http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6 -b14/java/net/Socket.java – RMachnik
我想查看類Socket和Server套接字的方法定義,是否有可能? – user3085866