问题描述
我想用Java编程一个非常简单的Server-Client对,这意味着我有一个服务器,可以在显示字符串的localhost / port下使用。因此,如果我打开网站,它会显示类似以下内容:
Hello World
Hi
How are you?
所有客户都使用相同的程序,但是他们都看到完全相同的页面。每个客户可以在需要时将当前页面添加几行。
我尝试了很多研究,但是还没有找到一个很好的例子。
此刻,我的程序如下所示: 服务器:
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.socket;
public class DomServer {
public static void main(String[] args) throws IOException {
// don't need to specify a hostname,it will be the current machine
ServerSocket ss = new ServerSocket(7777);
System.out.println("ServerSocket awaiting connections...");
Socket socket = ss.accept(); // blocking call,this will wait until a connection is attempted on this port.
System.out.println("Connection from " + socket + "!");
// get the input stream from the connected socket
InputStream inputStream = socket.getInputStream();
// create a DataInputStream so we can read data from it.
DataInputStream dataInputStream = new DataInputStream(inputStream);
// read the message from the socket
String message = dataInputStream.readUTF();
System.out.println("The message sent from the socket was: " + message);
System.out.println("Closing sockets.");
//ss.close();
//socket.close();
}
}
客户:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.socket;
public class DomClient {
public static void main(String[] args) throws IOException {
// need host and port,we want to connect to the ServerSocket at port 7777
Socket socket = new Socket("localhost",7777);
System.out.println("Connected!");
// get the output stream from the socket.
OutputStream outputStream = socket.getoutputStream();
// create a data output stream from the output stream so we can send data
// through it
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
System.out.println("Sending string to the ServerSocket");
// write the message we want to send
boolean terminate = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(system.in));
while(!terminate) {
String text = reader.readLine();
if(text.equals("end")) {
terminate = true;
}
dataOutputStream.writeUTF(text);
dataOutputStream.flush(); // send the message
}
dataOutputStream.close(); // close the output stream when we're done.
System.out.println("Closing socket and terminating program.");
socket.close();
}
}
它是该版本的修改后的副本:https://gist.github.com/chatton/8955d2f96f58f6082bde14e7c33f69a6
此刻,我遇到的问题是,当我输入第三行时,连接会自行关闭。我正在获取java.net.socketException:管道损坏(写入失败)。 而且,我不知道如何解决消耗性字符串网站的问题。
有人在编写类似的东西吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)