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