標籤:
先運行伺服器,再運行用戶端時得到伺服器發送到的hello world!資訊.
伺服器代碼:
import java.io.*;
import java.net.*;
public class HelloServer{
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket = null;
PrintWriter out = null;
try{
serverSocket = new ServerSocket(9999);
}
catch(IOException e)
{
System.err.println("Counld not listen on port:9999");
System.exit(1);
}
Socket clientSocket = null;
try{
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.err.println("Accept failed");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(),true);
out.println("hello world!");
clientSocket.close();
serverSocket.close();
}
}
用戶端代碼:
import java.io.*;
import java.net.*;
public class HelloClient{
public static void main(String args[]) throws IOException
{
Socket helloSocket = null;
BufferedReader in = null;
try{
helloSocket = new Socket("172.20.223.73",9999);
in = new BufferedReader(new InputStreamReader(helloSocket.getInputStream()));
}
catch(UnknownHostException e){
System.err.println("Don‘t know about host:localhost!");
System.exit(1);
}
catch(IOException e)
{
System.err.println("Couldn‘t get I/O for the connection");
System.exit(1);
}
System.out.println(in.readLine());
in.close();
helloSocket.close();
}
}
Leo Chin出處:http://www.cnblogs.com/hnrainll/本部落格文章,大多系網路中收集,轉載請註明出處相關標籤:嵌入式培訓、嵌入式開發、嵌入式學習
Java網路編程的簡單應用 常式