欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Socket(1)--简单例子

程序员文章站 2022-04-09 13:14:34
...
[size=large]代码例子:[/size]

package com.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* 服务端
*
* @author yale
*
*/
public class TcpServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(5000);

Socket socket = ss.accept();//等待接受 阻塞

OutputStream os = socket.getOutputStream();

os.write("hello client ".getBytes());

InputStream in = socket.getInputStream();

byte[] buffer = new byte[1024];

int length = 0;

while (-1 != (length = in.read(buffer, 0, buffer.length)))
{
String str = new String(buffer, 0, length);
System.out.println(str);
}
os.close();
in.close();
socket.close();

}
}




package com.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端
* @author yale
*
*/
public class TcpClient
{
public static void main(String[] args) throws Exception
{
Socket socket =new Socket("127.0.0.1",5000);

OutputStream os = socket.getOutputStream();

os.write("hello server ".getBytes());

InputStream in = socket.getInputStream();

byte[] buffer = new byte[1024];

int length = 0;

while (-1 != (length = in.read(buffer, 0, buffer.length)))
{
String str = new String(buffer, 0, length);
System.out.println(str);
}
os.close();
in.close();
socket.close();


}
}