java socket tcp(服务器循环检测)

时间:2021-07-01 15:58:00

刚才看了下以前写了的代码,tcp通信,发现太简单了,直接又摘抄了一个,运行

博客:http://blog.csdn.net/zhy_cheng/article/details/7819659

优点是服务器循环检测,客户端间歇性发送,缺点是代码杂糅在一块,不太容易看懂,大概明白它是通过方法重载实现的:

服务器代码:

建立ServiceSocket.java,ServiceSocket代码:

package com.swust.udp;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; public class ServiceSocket extends Thread{ public Socket sock;
public ServiceSocket(Socket sock)
{
this.sock=sock;
} public void run()
{
try{
OutputStream os=sock.getOutputStream();
InputStream is=sock.getInputStream();
os.write("Hello这里是来自服务器的消息".getBytes());
byte []buf=new byte[100];
int len=is.read(buf);
System.out.println(new String(buf,0,len));
os.close();
is.close();
sock.close();
}
catch(Exception e)
{ }
}
public static void main(String[] args) {
// TODO Auto-generated method stub try {
ServerSocket ss=new ServerSocket(6000); //循环扫描,没有关闭:ss.close();
while(true)
{
Socket s=ss.accept(); new ServiceSocket(s).start();
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

客户端代码:

建立ClientSocket.java,ClientSocket代码:

package com.swust.udp;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket; public class ClientSocket { public static void main(String []args)
{
try {
Socket s=new Socket(InetAddress.getByName(null),6000);//"localhost" "127.0.0.1s"
OutputStream os=s.getOutputStream();
InputStream is=s.getInputStream();
byte []buf=new byte[100];
int len=is.read(buf);
System.out.println(new String(buf,0,len));
os.write("Hello,我是客户端的消息".getBytes());
Thread.sleep(100);
os.close();
is.close();
s.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }