你好在互聯網上的程序員。我目前正在瀏覽一本操作系統手冊,並且有一些練習涉及以下代碼片段。服務器和客戶端交互
這是服務器代碼
import java.net.*;
import java.io.*;
public class DateServer{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true) {
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
// write the Date to the socket
pout.println(new java.util.Date().toString());
// close the socket and resume
// listening for connections
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
這是客戶端代碼
import java.net.*;
import java.io.*;
public class DateClient{
public static void main(String[] args) {
try {
//make connection to server socket
Socket sock = new Socket("127.0.0.1",6013);
InputStream in = sock.getInputStream();
BufferedReader bin = new
BufferedReader(new InputStreamReader(in));
// read the date from the socket
String line;
while ((line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
sock.close();
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
所以我的理解服務器創建套接字,並寫日期值給它。然後客戶端變長並連接到服務器並寫出該套接字中的值。我是否正確解釋此代碼?這是我第一次使用socket。
現在爲我的實際問題。我想讓客戶端連接到服務器(並打印出一條表示您已連接的消息),然後能夠將值發送到服務器,以便服務器可以處理它。我會如何去做這件事?我已經試過修改DataOutputStream和DataInputStream,但我從來沒有使用過。任何幫助將不勝感激。
本網站上這樣的例子很多。特別關注最近關於聊天客戶端的問題。 – KevinO