JAVA问题:用socket编写一个服务器端程序

2024-12-04 09:25:44
推荐回答(1个)
回答(1):

服务端:

	ServerSocket serverSocket = new ServerSocket(2008);

while (true) {
Socket socket = serverSocket.accept();
MyThread thread = new MyThread(socket);
thread.start();
}
public class MyThread extends Thread {
private Socket socket;

public MyThread(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
super.run();
try {
InputStream is = socket.getInputStream();

BufferedReader bufReader = new BufferedReader(new InputStreamReader(is));
String line = "";
String s = "";
while ((s = bufReader.readLine()) != null) {
line = line + s;
}
System.out.println("接收到:" + line);

} catch (IOException e) {
e.printStackTrace();
}
}

}客户端:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket=new Socket("192.168.0.101", 2008);
OutputStream out=socket.getOutputStream();
PrintWriter pw=new PrintWriter(new OutputStreamWriter(out));
pw.print("12345上山打老虎");
pw.flush();
pw.close();
out.close();
}