服务器部分:
package com
.softeem
.inetAddress
;
import java
.io
.DataInputStream
;
import java
.io
.DataOutputStream
;
import java
.io
.IOException
;
import java
.net
.ServerSocket
;
import java
.net
.Socket
;
import javax
.swing
.JOptionPane
;
public class Test4_server {
public static void main(String
[] args
) throws IOException
{
ServerSocket ss
= new ServerSocket(6666);
System
.out
.println("等待客户端连接。。。。");
Socket s
= ss
.accept();
System
.out
.println("连接成功!");
Message1 m
= new Message1(s
);
new Thread(m
,"发送").start();
new Thread(m
,"接收").start();
}
}
class Message1 implements Runnable{
Socket s
;
public Message1(Socket s
){
this.s
= s
;
}
public void run() {
String name
= Thread
.currentThread().getName();
try {
if(name
.equals("发送")){
while(true){
DataOutputStream dos
= new DataOutputStream(s
.getOutputStream());
String str
= JOptionPane
.showInputDialog("请输入你需要发送的消息:");
System
.out
.println("服务器:"+str
);
dos
.writeUTF(str
);
}
}else{
while(true){
DataInputStream dis
= new DataInputStream(s
.getInputStream());
System
.out
.println("从客户端读取了:"+dis
.readUTF());
}
}
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
客户端部分:
package com
.softeem
.inetAddress
;
import java
.io
.DataInputStream
;
import java
.io
.DataOutputStream
;
import java
.io
.IOException
;
import java
.net
.Socket
;
import java
.net
.UnknownHostException
;
import javax
.swing
.JOptionPane
;
public class Test4_client {
public static void main(String
[] args
) throws UnknownHostException
, IOException
{
Socket s
= new Socket("192.168.5.113",6666);
Message2 m
= new Message2(s
);
new Thread(m
,"接收").start();
new Thread(m
,"发送").start();
}
}
class Message2 implements Runnable{
Socket s
;
public Message2(Socket s
){
this.s
= s
;
}
public void run() {
String name
= Thread
.currentThread().getName();
try {
if(name
.equals("接收")){
while(true){
DataInputStream dis
= new DataInputStream(s
.getInputStream());
System
.out
.println("从服务器读取了:"+dis
.readUTF());
}
}else{
while(true){
DataOutputStream dos
= new DataOutputStream(s
.getOutputStream());
String str
= JOptionPane
.showInputDialog("请输入你需要发送的消息:");
System
.out
.println("服务器:"+str
);
dos
.writeUTF(str
);
}
}
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
转载请注明原文地址:https://tech.qufami.com/read-28238.html