Java网络编程入门SocketServer与Socket
发布时间:2020-05-30 13:25:00 所属栏目:Java 来源:互联网
导读:Java网络编程入门SocketServer与Socket
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
*@ClassName:Server
*@author: chenyoulong
*@date :2012-7-30 上午10:35:09
*@Description:TODO
*/
public class SendServer {
/**
* @throws IOException
* @Title: main
* @Description: TODO
* @param @param args
* @return void
* @throws
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket server=new ServerSocket(8888);
System.out.println("server start");
Socket sock=server.accept();
sock.setSoTimeout(6000); //服务器端设置连接超时时间,该操作只对读取(read)操作有效。
//读取
//字节流的形式读取
// 优缺点分析,弱点:受byte[]大小的限制 ,优点:不受回车符(r)和换行符(n)限制
InputStream input=sock.getInputStream();
byte[] buf =new byte[1024];
System.out.println("InputStream==="+input);
if(input!=null){
int len=input.read(buf);
ToolKit.writeLog(SendServer.class.getName(),"服务器端收到的报文:n"+new String(buf,len));
}
/* //字符流的形式读取
//(遇到换行符或者回车符就终止,还是谨慎使用)
BufferedReader read=new BufferedReader(new InputStreamReader(sock.getInputStream()));
String readStr=null;
if((readStr=read.readLine())!=null){
ToolKit.writeLog(Server.class.getName(),"服务器端收到的报文:n"+readStr);
}
if(read!=null) read.close();
*/
/*//输出
String outStr="我是server服务器端";
BufferedWriter write=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
if(outStr!=null){
write.write(outStr);
}
if(write!=null) write.close();*/
//挂关闭资源
if(sock!=null) sock.close();
if(server!=null) server.close();
}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
/**
*@ClassName:ReceiveClient
*@author: chenyoulong
*@date :2012-8-3 下午2:17:26
*@Description:TODO
*/
public class ReceiveClient {
private final String IP=Setting.RECEIVE_IP;
private final int PORT=Setting.RECEIVE_PORT;
private Logger log = Logger.getLogger(Sender.class.getName());
//发送
/**
* @throws Exception
* 发送报文
* @Title: send
* @Description: TODO
* @param @param reqMessage
* @return void
* @throws
*/
public void send(String reqMessage) throws Exception{
Socket sock=null;
BufferedOutputStream out=null;
try {
sock=new Socket();
SocketAddress sockAdd=new InetSocketAddress(IP,PORT);
sock.connect(sockAdd,2000); //客户端设置连接建立超时时间
out=new BufferedOutputStream(sock.getOutputStream());
out.write(reqMessage.getBytes());
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
log.error("网络连接异常"+Strings.getStackTrace(e));
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("网络连接异常n"+Strings.getStackTrace(e));
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
}
if(sock!=null){
try {
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//接收
public String reiceve() throws Exception{
Socket sock=null;
BufferedInputStream in=null;
try {
sock=new Socket(IP,PORT);
in = new BufferedInputStream(sock.getInputStream());
if ((sock == null) || (in == null)) {
throw new Exception("套接口无效,无法读取数据");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bts = new byte[10000];
int totalLen = 0,len = 0;
while ((len = in.read(bts,totalLen,1000)) != -1) {
totalLen += len;
}
String result = new String(bts); //注意字符编码
return result.trim();
}
//main函数示例
public static void main(String[] args){
//发送报文
//发送
String str="我是客户端!"
try {
new ReceiveClient().send(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//接收报文
/*try {
String recStr=new Receiver().reiceve();
System.out.println("客户端接收到的结果=="+recStr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
/**
*@ClassName:ThreadSocket
*@author: chenyoulong
*@date :2012-8-1 上午10:00:41
*@Description:TODO
*/
public class ThreadSocket implements Runnable {
private Socket sock;
public ThreadSocket(Socket sock){
this.sock=sock;
}
/*
* <p>Title: run</p>
* <p>Description: </p>
* @see java.lang.Runnable#run()
*/
public void run() {
// TODO Auto-generated method stub
InputStream input=null;
try {
input = sock.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* //字符流的形式读取(遇到换行符或者回车符就终止,还是谨慎使用)
BufferedReader read=new BufferedReader(new InputStreamReader(input));
String readStr=null;
try {
if((readStr=read.readLine())!=null){
System.out.println("服务器端收到的报文:n"+readStr);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(read!=null) {
try {
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
//字节流
byte[] buf = new byte[1024];
if (input != null) {
int len=0;
try {
len = input.read(buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("服务器端收到的报文:n"+ new String(buf,len));
}
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*@ClassName:OnRunSendServer
*@author: chenyoulong
*@date :2012-8-1 上午10:06:28
*@Description:TODO
*/
public class OnRunSendServer {
/**
* @throws IOException
* @Title: main
* @Description: TODO
* @param @param args
* @return void
* @throws
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
try {
server = new ServerSocket(8888);
System.out.println("send服务器start!");
Socket sock = null;
while (true) {
sock = server.accept();
sock.setSoTimeout(12000);//设置读取连接超时时间
ThreadSocket tsock = new ThreadSocket(sock);
new Thread(tsock).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}/*finally{ //这里还是不要finally关闭ServerSocket为好,防止某个socket连接超时导致整个ServerSocket都关闭了。
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Android添加触摸手势识别监听
- jpa – 必须在ConnectionDriverName属性“如何解决它?”中
- java – 用于j2me“回合制”游戏的Gameloop
- java – 获取List中特定元素的数量
- java – 如何配置FindBugs maven插件以仅检查@Nonnull之类的
- 使用Java在Google App Engine中分页
- 如何在JMX中使用getSystemCpuLoad()
- java-如何在Eclipse中指定要包含在.WAR文件中的内容
- 使用java执行命令简易封装类
- java – JVM Spec,JVM Implementation,JVM Runtime之间的区
