简单Socket代码,理解Socket

[b]服务器端Server[/b][color=red][/color][size=large][/size]
package com.Socket;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {

/**
* @param args
*/
public static void main(String[] args) {
ServerSocket svrsoc = null;
Socket soc = null;
DataInputStream in = null;
PrintStream out = null;
InetAddress clientIP = null;
String str = null;

try {
svrsoc = new ServerSocket(8000);
System.out.println("Server start.....");
soc = svrsoc.accept();

//用于接收客户端发来的数据的输入流
in = new DataInputStream(soc.getInputStream());
//用于向客户端发送数据的输出流
out = new PrintStream(soc.getOutputStream());
clientIP = soc.getInetAddress();
System.out.println("Client IPAddress:"+clientIP);
out.println("Welcome......");
str = in.readLine();
while(!str.equals("quit")){
System.out.println("Client said:"+str);
str = in.readLine();
}
System.out.println("Client want to leave....");
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
in.close();
out.close();
soc.close();
svrsoc.close();
System.exit(0);
}catch (IOException e) {
e.printStackTrace();
}
}
}

}

[b]客户端端Client[/b][color=red][/color][size=large][/size]
package com.Socket;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient {
public static void main(String[] args) {
Socket soc = null;
DataInputStream in = null;
PrintStream out = null;
DataInputStream sysin = null;
String strin = null;
String strout = null;

try {
soc = new Socket("localhost", 8000);
System.out.println("Connecting to the Server....");
//获取输入流,用于接收服务器端发送来的数据
in = new DataInputStream(soc.getInputStream());
//获取输出流,用于客户端向服务器端发送数据
out = new PrintStream(soc.getOutputStream());
strin = in.readLine();
System.out.println("Server said:" + strin);
//用户输入流
sysin = new DataInputStream(System.in);
strout = sysin.readLine();
while (!strout.equals("quit")) {
out.println(strout);
strout = sysin.readLine();
}
out.println(strout);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
} else if (out != null) {
out.close();
} else if (sysin != null) {
sysin.close();
} else if (soc != null) {
soc.close();
}

System.exit(0);
} catch (IOException e) {
}
}
}
}

[b]实现客户端Client输入字符串,服务器Server端显示输出[/b]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值