ari*_*jit -1 java sockets networking network-programming serversocket
我正在写一个服务器 - 客户端聊天程序.
这是我的代码
服务器:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
String response = "Hello " + s.getInetAddress() + " on port " + s.getPort()
+ "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort()
+ "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
System.out.write(response.getBytes());
InputStream in = s.getInputStream();
System.out.println("from client");
int z = 0;
while ((z = in.read()) != -1) {
System.out.write(z);
}
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
客户:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("192.xxx.x.xxx", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
+ socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
int b = 0;
OutputStream os = System.out;
while ((b = bfINPUT.read()) != -1) {
os.write(b);
}
OutputStream osNew = socket.getOutputStream();
String s = "This Is The Client"; // data to be sent
osNew.write(s.getBytes());
os.write(s.getBytes());
}
Run Code Online (Sandbox Code Playgroud)
我通过我的程序连接了它们.
但现在我想知道如何从客户端将一些数据发送回服务器?
什么是客户端的代码(用于向服务器发送数据)以及用于显示从控制台(服务器)上的客户端接收的数据的服务器的代码?
PS-我是网络编程的新手.请不要批评我的编码风格:P
使用服务器流
OutputStream os = socket.getOutputStream();
Run Code Online (Sandbox Code Playgroud)
而不是客户端控制台输出流
OutputStream os = System.out;
Run Code Online (Sandbox Code Playgroud)
在客户端写回服务器.
并且在服务器端使用客户端流以相同的方式从客户端读取.
InputStream in = s.getInputStream();
Run Code Online (Sandbox Code Playgroud)
我已经在服务器 - 客户端通信上发布了示例代码.阅读它是为了你的学习.