我是Java的成员,所以我需要获得这项工作? 我做类,进入这个我添加了主要的方法,我粘贴这个代码,但这是行不通的。 在服务器类给我一些关于最后变量的错误。我什么都不懂。客户端 - 服务器套接字
客户端类
//Creating the client socket:
Socket socket = new Socket();
//Binding to the local socket address:
InetAddress localIpAddress = InetAddress.getByName ("0.0.0.0");
int localIpPort = 0;
SocketAddress localSocketAddress = new InetSocketAddress (localIpAddress, localIpPort);
socket.bind (localSocketAddress);
//Connecting to the remote socket address:
InetAddress remoteIpAddress = InetAddress.getByName ("localhost");
int remoteIpPort = 20000;
SocketAddress remoteSocketAddress = new InetSocketAddress (remoteIpAddress, remoteIpPort);
socket.connect (remoteSocketAddress);
//Receiving and/or sending data through inbound and outbound streams:
BufferedReader reader = new BufferedReader (new InputStreamReader (socket.getInputStream()));
BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (socket.getOutputStream()));
String request = "Hello";
writer.write (request);
writer.newLine();
// Do not forget to flush
writer.flush();
// Reading the response
String response = reader.readLine();
//Shutting-down the inbound and outbound streams:
socket.shutdownInput();
socket.shutdownOutput();
//Closing the socket:
socket.close();
[...]
服务器类
//Creating the server socket:
ServerSocket socket = new ServerSocket();
//Binding to the local socket address -- this is the one the clients should be connecting to:
InetAddress localIpAddress = InetAddress.getByName ("0.0.0.0");
int localIpPort = 20000;
SocketAddress localSocketAddress = new InetSocketAddress (localIpAddress, localIpPort);
socket.bind (localSocketAddress);
while (true) {
//For each connection accepting a client socket, and:
Socket client = socket.accept();
// Starting a new Thread for each client
new Thread() {
public void run() {
try {
//Receiving and/or sending data;
BufferedReader reader = new BufferedReader (new InputStreamReader (client.getInputStream()));
BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (client.getOutputStream()));
// Reading the request
String request = reader.readLine();
// Write the response
String response = "Welcome";
writer.write(response);
writer.newLine();
// Do not forget to flush!
writer.flush();
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
//Closing the server socket;
socket.close();
最后一个错误是socket.close()是无法访问的代码?在服务器类 – LXSoft
当然。 'while(true){...'形成一个无限循环。所以在循环之后加上'close'是没有意义的。 – Holger
我在while结束时移动该行并且没有更多错误 – LXSoft