本程序中,客户端输入一个数据饼传送到服务器,服务器处理该数据返回结果,实现一对一通讯
客户端:client.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import java.io.*;
import java.net.*;
/**
*
* @author Administrator
*/
public class Client {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
Socket connetcToServer=new Socket("localhost",5500);//连接本机端口
//将数据输入流连接到socket上
DataInputStream inFromServer=new DataInputStream(connetcToServer.getInputStream());
//将数据输出流连接到socket上
DataOutputStream outToServer=new DataOutputStream(connetcToServer.getOutputStream());
System.out.println("输入半径值 发送到服务器,输入bye结束");
String outStr,inStr;
boolean goon=true;
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
while(goon){
outStr=buf.readLine();//读取用户的输入
outToServer.writeUTF(outStr);//写到socket中
outToServer.flush();//清空缓冲区,立即发送
inStr=inFromServer.readUTF();//从socket中读数据
if(!inStr.equals("bye"))
System.out.println("从服务器返回的结果是"+inStr);
else
goon=false;
}
inFromServer.close();
outToServer.close();
connetcToServer.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
服务器端:Server.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import java.io.*;
import java.net.*;
/**
*
* @author Administrator
*/
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
System.out.println("等待连接...");
//创建服务端套接字,端口号5500要与客户端相同
ServerSocket ServerSocket=new ServerSocket(5500);
Socket connectToClient=ServerSocket.accept();
System.out.println("连接来自于"+connectToClient.getInetAddress().getHostAddress());
DataInputStream inFromClient=new DataInputStream(connectToClient.getInputStream());
DataOutputStream outToClient=new DataOutputStream(connectToClient.getOutputStream());
String str;
double radius,area;
boolean goon=true;
while(goon)
{
str=inFromClient.readUTF();
if(!str.equals("bye")){
radius=Double.parseDouble(str);
System.out.println("接收到的半径是"+radius);
area=radius*radius*Math.PI;
str=Double.toString(area);
outToClient.writeUTF(str);
outToClient.flush();
System.out.println("圆面积"+str+"已经发送");
}
else{
goon=false;
outToClient.writeUTF("bye");
outToClient.flush();
}
}
inFromClient.close();
outToClient.close();
ServerSocket.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
实现效果: