JAVA中如何监听一个端口来进入收和发信息!

2024-12-15 10:43:50
推荐回答(3个)
回答1:

String ip = "127.0.0.1";
int port = 1234;
try {
Socket socket = new Socket(ip, port);
socket.setSoTimeout(5539900);
java.io.OutputStream out = socket.getOutputStream();

byte[] date = "hello world".getBytes();
out.write(data);
out.flush();
byte[] buffer = new byte[1024];
int len = -1;
java.io.FileOutputStream fout = new java.io.FileOutputStream(
"d:/response.txt");
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
java.io.InputStream in = socket.getInputStream();
while ((len = in.read(buffer, 0, buffer.length)) > 0) {
bout.write(buffer, 0, len);
}
in.close();
bout.flush();
bout.close();

byte[] rdata = bout.toByteArray();
System.out.println(new String(rdata));

fout.write(rdata);
fout.flush();
fout.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

服务器端的

ServerSocket ss = new ServerSocket(1234);
Socket socket=null;
BufferedReader in;
PrintWriter out;

while (true) {
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
String line = in.readLine();
out.println("you input is :" + line);
out.close();
in.close();
socket.close();
}

回答2:

import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server{
public Server() throws Exception{
ServerSocket socket=new ServerSocket(1000); //在1000端口监听
while(true){
Socket s=socket.accept();
while(!s.isConnected()){}
new Processor(s).start();
}
}
public static void main(String args[]) throws Exception{
new Server();
}
}
class Processor extends Thread{
Socket s=null;
public Processor(Socket s) throws Exception{
this.s=s;
}
public void run(){
try{
ObjectInputStream obj=new ObjectInputStream(s.getInputStream());
JOptionPane.showMessageDialog(null,(String)obj.readObject());
obj.close();
}catch(Exception e){}
}
}

回答3:

你看过那个聊天视频吗?? 就是制作一个聊天程序的
就是多线程啊 没有太多的东西
socket啊 你上网看看吧 然后你就明白了