当前位置: 技术问答>java相关
问一个关于socket的小问题!
来源: 互联网 发布时间:2015-10-17
本文导语: 请问用java的Socket编程,有没有办法得到有消息到达时的消息,像windows编程中的receive()函数,初学网络编程,请高人指教! | package netlearn; import java.net.*; import java.io.*; public class SimpleServer...
请问用java的Socket编程,有没有办法得到有消息到达时的消息,像windows编程中的receive()函数,初学网络编程,请高人指教!
|
package netlearn;
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) {
ServerSocket s = null;
Socket s1;
String sendString = "Hello Net World!";
OutputStream s1out;
DataOutputStream dos;
// Register your service on port 5432
try {
s = new ServerSocket(5432);
} catch (IOException e) { }
// Run the listen/accept loop forever
while (true) {
try {
// Wait here and listen for a connection
s1=s.accept();
// Get a communication stream for soocket
s1out = s1.getOutputStream();
dos = new DataOutputStream (s1out);
// Send your string! (UTF provides machine-independent format)
dos.writeUTF(sendString);
// Close the connection, but not the server socket
s1out.close();
s1.close();
} catch (IOException e) { }
}
}
}
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) {
ServerSocket s = null;
Socket s1;
String sendString = "Hello Net World!";
OutputStream s1out;
DataOutputStream dos;
// Register your service on port 5432
try {
s = new ServerSocket(5432);
} catch (IOException e) { }
// Run the listen/accept loop forever
while (true) {
try {
// Wait here and listen for a connection
s1=s.accept();
// Get a communication stream for soocket
s1out = s1.getOutputStream();
dos = new DataOutputStream (s1out);
// Send your string! (UTF provides machine-independent format)
dos.writeUTF(sendString);
// Close the connection, but not the server socket
s1out.close();
s1.close();
} catch (IOException e) { }
}
}
}