互联网上的程序员你好。我目前正在逐步浏览一本操作系统书籍,有一些练习涉及以下代码片段。
这是服务器代码
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);
}
}
}
因此,据我了解,服务器正在创建一个套接字并向其中写入日期值。然后,客户端将很长地连接到服务器并写出该套接字中的值。我是否正确解释此代码?这是我第一次使用插座。
现在谈谈我的实际问题。我想让客户端连接到服务器(并打印出一条消息,说明您已连接),然后能够将值发送到服务器,以便服务器可以处理它。我将如何做到这一点?我尝试过修改DataOutputStream和DataInputStream,但我以前从未使用过。任何帮助将不胜感激。
你是对的。服务器写入套接字,客户端从套接字读取。你想扭转这种情况。
服务器应如下所示:
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true)
{
Socket client = sock.accept();
InputStream in = client.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
// read the date from the client socket
String line;
while ((line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
client.close();
}
客户端应如下所示:
try
{
// make connection to server socket
Socket sock = new Socket("127.0.0.1", 6013);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// send a date to the server
out.println("1985");
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}