본문 바로가기

Java프로그래밍/예제문제

네트워킹 예제

반응형
SMALL

Server.java



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package univ.inu.embedded;

import java.net.*;
import java.io.*;

public class Server 
{

	public Server()
	{
		
		try 
		{
			ServerSocket ss = new ServerSocket(9000);
			while (true)
			{
				Socket s = ss.accept();
				
				(new ServerThread(s)).start();
			}
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		
	}
	
	
	public static void main(String[] args) 
	{
		new Server();
	}

}



ServerThread.java



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package univ.inu.embedded;

import java.net.*;
import java.io.*;

public class ServerThread extends Thread 
{

	Socket s = null;
	
	public ServerThread()
	{
		
	}
	public ServerThread(Socket _s)
	{
		s = _s;
	}
	public void run()
	{

		try 
		{
			BufferedReader br =
			new BufferedReader(new InputStreamReader(s.getInputStream()));
			BufferedWriter bw =
			new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
			
			while (true)
			{
				bw.write("I am server. Do you hear me?\n");
				bw.flush();
			
				String s = br.readLine();
				System.out.println("Server received :: "+s);
				
				Thread.sleep(10000);
				
			}

		} catch (IOException | InterruptedException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}



Client.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package univ.inu.embedded;

import java.net.*;
import java.io.*;

public class Client 
{
	
	public Client()
	{
		
		Socket s;
		try 
		{
			s = new Socket("127.0.0.1", 9000);
			BufferedReader br = 
			new BufferedReader(new InputStreamReader(s.getInputStream()));
					
			BufferedWriter bw =
			new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

			while (true)
			{
				String str = br.readLine();
				System.out.println("Client received:: "+str);
						
				bw.write("this is client.\n");
				bw.flush();
				}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	

	public static void main(String[] args) 
	{

		new Client();
		
	}

}
반응형
LIST

'Java프로그래밍 > 예제문제' 카테고리의 다른 글

network pingpong serer  (0) 2016.05.17
network pingpong client  (0) 2016.05.17
혼자 탁구 소스코드  (0) 2016.04.29
당구프로그램 예제  (0) 2016.04.15
Timer : TmerLogic and Test program  (0) 2016.04.08