Java Socket网络编程Client端详解

时间:2023-03-09 19:57:53
Java Socket网络编程Client端详解

此类实现客户端套接字(也可以就叫“套接字”)。套接字是两台机器之间的通信端点。

Socket client = new Socket(ip,port);//创建一个流套接字并将其连接到指定 IP 地址的指定端口号。

以下为完整的客户端示例:

SocketClientDemo.java

public class SocketClientDemo
{
/**
* 向指定的地址发送请求数据
* @param ipAddr
* @param reqData
*/
public void sendReq(String ipAddr,String reqData)
{
Socket client = null;
BufferedReader br = null;
BufferedOutputStream bos = null;
String respStr = ""; //设置字符集编码格式
String characterCoding = "GBK"; //将ip:port 类型的字符串拆分
int dotPos = ipAddr.indexOf(":");
String ip = ipAddr.substring(0, dotPos).trim();
int port = Integer.parseInt(ipAddr.substring(dotPos+1).trim()); try
{
client = new Socket(ip,port);
//设置发送等待时间(单位:s)
client.setSoLinger(true, 5); //设置超时时间(单位:ms)
client.setSoTimeout(5000); //从client端获取输出流
bos = new BufferedOutputStream(client.getOutputStream());
bos.write(reqData.getBytes(characterCoding));
bos.flush(); br = new BufferedReader(new InputStreamReader(client.getInputStream()));
respStr = br.readLine();
System.out.println("respStr is:>>>>>>"+respStr);
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bos!=null)
{
try
{
bos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(client!=null)
{
try
{
client.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

测试类代码:

SocketClientTest.java

public class SocketClientTest
{ /**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SocketClientDemo client = new SocketClientDemo();
client.sendReq("192.168.1.136:9997", "this is socket client!");
}
}