
用Java 的socket实现客户端的功能
我想用java实现一个客户端,利用TCP/IP协议向远程的已经存在的服务器发送,和接收数据该怎么实现?也就是说服务器端给我了Ip地址和端口号,我写个程序和它连接,向它发送...
我想用java 实现一个客户端,利用TCP/IP协议向远程的已经存在的服务器发送,和接收数据该怎么实现?也就是说服务器端给我了Ip地址和端口号,
我写个程序和它连接,向它发送数据同时也要接收服务器发回来的数据。请问各位大牛这个该怎么实现?最好有源代码,没源代码说下思路也可以,谢谢了! 展开
我写个程序和它连接,向它发送数据同时也要接收服务器发回来的数据。请问各位大牛这个该怎么实现?最好有源代码,没源代码说下思路也可以,谢谢了! 展开
1个回答
推荐于2017-09-10 · 知道合伙人数码行家
关注

展开全部
//服务端程序:
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
new TCPServer().init();
}
@SuppressWarnings("static-access")
private void init() throws IOException{
@SuppressWarnings("resource")
ServerSocket server = new ServerSocket(1000);
Socket client = null;
while(true){
try {
client = server.accept();
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
byte[] b = new byte[1024];
int len = 0;
String message = "";
while((len=bis.read(b))!=-1){
message = new String(b,0,len);
System.out.print("客户端:"+client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:" + message);
if("byte".equals(message.trim()))
client.close();
PrintWriter pw = new PrintWriter(client.getOutputStream(),true);
pw.println(message);
}
} catch (Exception e) {
System.err.println("客户端:"+client.getInetAddress().getLocalHost().getHostAddress()+" 已断开连接!");
}
}
}
}
//客户端程序:
import java.io.*;
import java.net.Socket;
public class TCPClient implements Runnable{
public static void main(String[] args) throws IOException {
new TCPClient().init();
}
private void init() throws IOException{
@SuppressWarnings("resource")
final Socket client = new Socket("127.0.0.1",1000);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String send = "";
while(true){
send = in.readLine();
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
if(!"byte".equals(send.trim()))
out.println(send);
else{
out.println(send);
System.exit(0);
}
new Thread(new TCPClient(){
@SuppressWarnings("static-access")
public void run(){
try {
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
byte[] b = new byte[1024];
int len = 0;
while((len=bis.read(b))!=-1){
System.out.println("服务器:" +client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:"+new String(b,0,len).trim());
}
} catch (IOException e) {
System.err.println("连接服务器失败!");
}
}
}).start();
}
}
public void run() {}
}
//服务器测试结果:
客户端:192.168.0.200发来消息:001 byte
客户端:192.168.0.200发来消息:byte
客户端:192.168.0.200 已断开连接!
客户端:192.168.0.200发来消息:adasd
客户端:192.168.0.200 已断开连接!
//客户端测试结果:
---001号客户端--
001 byte
服务器:192.168.0.200发来消息:001 byte
byte //001礼貌说跟服务器说byte
---002号客户端--
adasd //002客户端直接关闭程序
服务器:192.168.0.200发来消息:adasd
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询