求JAVA的监听5038端口的代码。。。
发布网友
发布时间:2023-06-26 10:35
我来回答
共2个回答
热心网友
时间:2023-10-17 16:09
服务端:
package com.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = null;
Socket socket = null;
try {
server = new ServerSocket(5038);
while(true){
System.out.println("正在监听...");
if((socket = server.accept()) != null){
System.out.println("接收到一个请求"+ socket.getRemoteSocketAddress());
new Thread(new OperThread(socket)).start();
}
}
} catch (IOException e) {
System.out.println("waiting");
}
if(!socket.isConnected()){
socket.close();
server.close();
}
}
}
class OperThread implements Runnable{
Socket socket = null;
BufferedReader br = null;
public OperThread(Socket socket) throws IOException {
this.socket = socket;
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
@Override
public void run() {
try {
String s = null;
while( (s = br.readLine()) != null){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端:
package com.socket;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter pw = null;
Scanner scanner = new Scanner(System.in);
try {
socket = new Socket("127.0.0.1",5038);
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
String s = null;
while((s = scanner.nextLine()) != null){
pw.println(s);
pw.flush();
}
} catch (Exception e) {
System.out.println("\nconnect error");
}finally{
if(pw != null){
pw.close();
}
try {
if(socket != null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
先开服务端,再开客户端。追问谢谢你的热心帮助,很感谢你,只是我在写JAVA的时候遇到某些小问题的时候很无助,你能否加我扣扣。 五5四7四9四60(百度有过水滤,只能写成这样) 我不会一直烦着你的, 真心希望你能加我。谢谢。
追答已加。
热心网友
时间:2023-10-17 16:10
能不能把问题描述的详细一点!