java网络编程,简单的客户端和服务器端

1.服务器端

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket; public class HelloWorldServer { public static void main(String[] args) {
ServerSocket server = null;
BufferedReader reader = null;
Socket client = null;
try {
server = new ServerSocket();//创建ServerSocket对象,并绑定端口
client = server.accept();//调用accept方法,等待客户端的连接
InputStream in = client.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String str = reader.readLine();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(client!=null){
client.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
} }

2.客户端

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner; public class HelloWorldClient { public static void main(String[] args) {
Socket client = null;
PrintWriter writer = null;
try {
client = new Socket("www.feifeishi.cn", );//www.feifeishi.cn是我的云服务器
OutputStream out = client.getOutputStream();
writer = new PrintWriter(out);
Scanner sc=new Scanner(System.in);
String aa=sc.nextLine();
writer.print(aa);
writer.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(writer!=null){
writer.close();
}
if(client!=null){
client.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
} }

3.运行

  将服务器端放到服务器上并运行

java网络编程,简单的客户端和服务器端

运行服务器端

java网络编程,简单的客户端和服务器端

正在等待客户端接入,然后本地运行客户端

java网络编程,简单的客户端和服务器端

控制台输入你好,然后服务器端接收并显示你好

java网络编程,简单的客户端和服务器端

4.拓展

TCP编程
   java.net.Socket
   java.net.ServerSocket
TCP编程的核心思路
   开发服务器端
   ServerSocket ss = new ServerSocket(9000)
   ss.accept();
   Socket s = new Socket("150.236.56.101", 9000)
java网络编程,简单的客户端和服务器端
 
上一篇:NPOI教程


下一篇:Codeforces Round #447 (Div. 2) C 构造