socket编程的简单例子

<div class="iteye-blog-content-contain" style="font-size: 14px">

实现简单的互相发信息

/*
* 客户端
*/
public class Client
{
private static final int PORT = 8089;
private static final String HOST = "127.0.0.1";

public static void main(String[] args){
System.out.println("客户端启动…");
System.out.println("当接收到服务器端字符为 \"END\" 的时候, 客户端将终止\n");

while(true){
Socket socket = null;
try
{
socket = new Socket(HOST,PORT);
//向服务器发送信息
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//接受服务器反馈信息
PrintWriter out = new PrintWriter(socket.getOutputStream());
//获取控制台输入的信息
System.out.print("请输入: \t");
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.println(str);
out.flush();

String read = input.readLine();
System.out.println("from Servcer: "+read);
if("END".equals(read)){
System.out.println("客户端关闭连接……");
Thread.sleep(500);
break;
}
input.close();
out.close();
} catch (Exception e)
{
System.out.println("客户端异常:" + e.getMessage());
}finally{
if(null != socket){
try
{
socket.close();
} catch (IOException e)
{
System.out.println("客户端 finally 异常:" + e.getMessage());
}
}
}
}
}
}

/*
* 服务端
*/
public class Server
{
public static final int PORT = 8089;

public static void main(String[] args)
{
System.out.println("服务器启动…\n");
ServerCode server = new ServerCode();
server.init();
}

@SuppressWarnings("resource")
public void init(){
try
{
ServerSocket serverSocket = new ServerSocket(PORT);
while(true){
Socket socket = serverSocket.accept();
try
{
// 读取客户端数据
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read = input.readLine();
System.out.println("from Client:"+read);

//向客户端发送信息
PrintWriter out = new PrintWriter(socket.getOutputStream());
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.println(str);
out.flush();

out.close();
input.close();
} catch (IOException e)
{
System.out.println("服务器 run 异常: " + e.getMessage());
}finally{
if(null!=socket){
try
{
socket.close();
} catch (IOException e)
{
socket = null;
System.out.println("服务端 finally 异常:" + e.getMessage());
}
}
}
}
} catch (IOException e)
{
System.out.println("服务器异常: " + e.getMessage());
}
}

}

</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值