java网路编程问题总结_Java网络编程问题

S端

import java.net.*;

import java.io.*;

public class TestServer extends Thread{

private ServerSocket serverSocket;

public TestServer(int port) throws IOException {

serverSocket = new ServerSocket(port);

serverSocket.setSoTimeout(10000);

}

public void run()

{

while(true)

{

try

{

System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");

Socket server = serverSocket.accept();

System.out.println("远程主机地址:" + server.getRemoteSocketAddress());

DataInputStream in = new DataInputStream(server.getInputStream());

System.out.println(in.readUTF());

DataOutputStream out = new DataOutputStream(server.getOutputStream());

out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!");

server.close();

}catch(SocketTimeoutException s)

{

System.out.println("Socket timed out!");

break;

}catch(IOException e)

{

e.printStackTrace();

break;

}

}

}

public static void main(String[] args) {

int port = Integer.parseInt("6066");

try {

Thread thread = new TestServer(port);      //class继承了Thread类

thread.run();

} catch (IOException e) {

e.printStackTrace();

}

}

}

C端

import java.net.*;

import java.io.*;

public class TestClient {

public static void main(String[] args) {

String serverName = "localhost";

int port = Integer.parseInt("6066");

try

{

System.out.println("连接到主机:" + serverName + " ,端口号:" + port);

Socket client = new Socket(serverName, port);

System.out.println("远程主机地址:" + client.getRemoteSocketAddress());

OutputStream outToServer = client.getOutputStream();

DataOutputStream out = new DataOutputStream(outToServer);

out.writeUTF("Hello from " + client.getLocalSocketAddress());

InputStream inFromServer = client.getInputStream();

DataInputStream in = new DataInputStream(inFromServer);

System.out.println("服务器响应: " + in.readUTF());

client.close();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

c6ee08bcf738cbc65f28d6c10017d926.png

请问老师,是因为端口号没设置对吗,还是两个JAVA程序不能模拟socket通信?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值