Java网络编程的简单应用 例程
生活随笔
收集整理的這篇文章主要介紹了
Java网络编程的简单应用 例程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先運行服務器,再運行客戶端時得到服務器發送到的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.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();
}
}
轉載于:https://www.cnblogs.com/hnrainll/archive/2011/10/18/2216057.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Java网络编程的简单应用 例程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在 Linux 中查找和删除重复文件
- 下一篇: BIOS和Bootloader的区别