package com.lishuaitcp.www;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端需要发送数据,同时需要接收服务端回送的数据
*
* @author Administrator
*
*/
public class TcpTest {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// 创建客户端对象
Socket s = new Socket("172.27.35.1", 1818);
// 创建输出流对象
OutputStream out = s.getOutputStream();
out.write("大家好哦,我是客户端对象".getBytes());
// 创建输入流对象,接收服务端回送回来的数据
InputStream in = s.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
len = in.read(buffer);
System.out.println(new String(buffer, 0, len));
}
}
package com.lishuaitcp.www;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpTest2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket ss = new ServerSocket(1818);
while (true) {
Socket s = ss.accept();
new Thread(new Sever(s)).start();
}
}
}
class Sever implements Runnable {
private Socket s;
public Sever(Socket s) {
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
InputStream in = s.getInputStream();
String ip = s.getInetAddress().getHostAddress();
int len = 0;
byte[] buffer = new byte[1024];
len = in.read(buffer);
System.out.println(ip + "----" + new String(buffer, 0, len));
OutputStream out = s.getOutputStream();
out.write("我接受到你发来的数据了".getBytes());
s.close();
} catch (Exception e) {
}
}
}
网友评论