Socket编程
来源:互联网 发布:网络协议分析pdf 编辑:程序博客网 时间:2024/06/10 12:00
服务器端:TcpServer
import java.io.*;
import java.net.*;
public class TcpServer {
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(1234);
soc = svrsoc.accept();
in = new DataInputStream(soc.getInputStream());
out = new PrintStream(soc.getOutputStream());
clientIP = soc.getInetAddress();
System.out.println("Client's IP address: " + 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(Exception e) {
System.out.println("Error: " + e);
}
}
}
客户端:TcpClient
import java.net.*;
import java.io.*;
public class TcpClient {
public static void main(String[] args) {
Socket soc = null;
BufferedReader in = null;
PrintWriter out = null;
String strin = null;
String strout = null;
try {
soc = new Socket("localhost",1234);
System.out.println("Connecting to Server...");
in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);
strin = in.readLine();
System.out.println("Server said: " + strin);
byte bmsg[] = new byte[20];
System.in.read(bmsg);
String msg = new String(bmsg,0);
msg = msg.trim();
while(!msg.equals("quit")) {
out.println(msg);
System.in.read(bmsg);
msg = new String(bmsg,0);
msg = msg.trim();
out.println(msg);
}
out.println(strout);
}catch(Exception e) {
System.out.println("Errer: " + e);
}
finally {
try{
in.close();
out.close();
soc.close();
System.exit(0);
}catch(Exception e){
System.out.println("Error: " + e);
}
}
}
}
先运行服务器端,再运行客户段。
这个例子很简单,而且有缺陷,但原理上是这样。
- socket编程--socket基本概念
- socket编程--socket基本概念
- socket编程
- socket编程
- Socket 编程
- socket编程
- Socket编程
- Socket编程
- Socket编程
- Socket编程
- SOCKET编程
- socket编程
- Socket编程
- socket编程
- Socket 编程
- Socket 编程
- socket 编程
- socket编程
- Aplix助NEC/松下Linux手机平台建设
- 从C++到C#,我遇到的几个问题
- 核心路由器十项性能指标
- 图片欲览--外键的创建--在浏览器在打开另一个窗口--生成。DLL文件
- oracle procedure and webservice
- Socket编程
- 三级关联菜单
- C++练习:已知三点,求过这三点的圆
- switch语句
- 学习oracle sql loader 的使用
- Video(http://www.enet.com.cn/article/2006/0704/A20060704124810.shtml)
- 架构师学习宝典:PHP 读物列表
- 利用FSO生成静态页
- 钢铁雄心II(HOI2)作弊码合辑